Original Post
🔒 Locked
C++ map
Advertisement
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.
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]
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]
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement