Jump to content
  • Advertisement


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


C++ map

This topic is 5245 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

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;

<< 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;
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

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!