Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 243
Faraway Avatar asked Apr 30 '13 03:04

Faraway


People also ask

How do you change the key of an unordered map?

You can use unordered_map::erase and unordered_map::insert to update a key. The average time complexity is O(1)(BTW, the worst is O(n)). If you are using C++17, you can also use unordered_map::extract to update a key.

How do I get the value of an unordered map?

unordered_map at() in C++ Both key and value can be of any type predefined or user-defined. unordered_map :: at(): This function in C++ unordered_map returns the reference to the value with the element as key k.

How do I add to an unordered map?

std::unordered_map::insert. Inserts new elements in the unordered_map. Each element is inserted only if its key is not equivalent to the key of any other element already in the container (keys in an unordered_map are unique). This effectively increases the container size by the number of elements inserted.

Are Keys sorted in unordered_map?

An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it.


1 Answers

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; 
like image 87
Yuushi Avatar answered Oct 18 '22 09:10

Yuushi