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.
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.
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.
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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With