C++ map

Started by
1 comment, last by Mr_Ridd 19 years, 10 months ago
Howzit How do I use a map? Basically getting data out of it. Is it similar to a vector? Shot
The ability to succeed is the ability to adapt
Advertisement
No, it''s completely different, being an associative array.

std::map<string, int> m; // map strings to intsm["foo"] = 4;m["bar"] = 97;m["sputnik"] = 1808;cout << m["foo"] << " " << m["bar"] << " " << m["sputnik"];


read up
Yes and no. There is an easy way to put data in mymap[key] = value;, but safe retrieval is slightly more complex, as you need to check whether the item sought is or isn't in the map.

std::map<KeyType, ValueType>::iterator it;it = mymap.find(key);if(it != mymap.end())   value = it->second;else   std::cerr << "Key not found" << std::endl;  


Using indexing syntax for element access may have unwanted side-effects, since if the key doesn't exist, an element is created.

Edit - so, in leiavoia's example, if you did cout << m["leiavoia"];, a new item with key "leiavoia" and value zero (default int) would be created, and a zero printed. Which may or may not be what you wanted.

[edited by - Fruny on June 11, 2004 1:38:04 AM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement