In unordered_map of C++11, how to update the value of a particular key?

Faraway picture Faraway · Apr 30, 2013 · Viewed 43.6k times · Source

In Java's hashmap:

map.put(key, new_value) 

will update the entry of key=key with new_value if it exists in the hashmap.

What's the correct way to do the similar thing in unordered_map of C++11?

I haven't found an API like updateXXX, and the documentation says the unordered_map::insert function will succeed only when there isn't any such pair with a key.

Answer

Yuushi picture Yuushi · Apr 30, 2013

If you know that the key is in the map, you can utilize operator[] which returns a reference to the mapped value. Hence it will be map[key] = new_value. Be careful, however, as this will insert a (key, new_value) if the key does not already exist in the map.

You can also use find which returns an iterator to the value:

auto it = map.find(key)
if(it != map.end()) 
    it->second = new_value;