In unordered_map of C++11, how to update the value of a particular key?
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;
If the type value
has no default constructor you can use:
map.emplace(key, new_value).first->second = new_value;
This also has all the other advantages of emplace vs [] operator and insert.