• Advertisement

Archived

This topic is now archived and is closed to further replies.

C++ map

This topic is 4971 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Howzit How do I use a map? Basically getting data out of it. Is it similar to a vector? Shot

Share this post


Link to post
Share on other sites
Advertisement
No, it''s completely different, being an associative array.

std::map<string, int> m; // map strings to ints


m["foo"] = 4;
m["bar"] = 97;
m["sputnik"] = 1808;

cout
<< m["foo"] << " "
<< m["bar"] << " "
<< m["sputnik"]
;


read up

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

  • Advertisement