Faraway
Faraway

Reputation: 1117

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.

Upvotes: 35

Views: 79434

Answers (4)

ravvis
ravvis

Reputation: 147

  1. Check if the key exists
  2. Update the value by referencing the key
if(map.count(key)){
  map[key] = value;
}

Upvotes: 0

N3UR0CHR0M
N3UR0CHR0M

Reputation: 313

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.

Upvotes: 4

RichardBruce
RichardBruce

Reputation: 671

I thought that Java's map.put inserted the element if it wasn't already in the map and updated it if it was in the map, see put:

put

public V put(K key, V value)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

This would be equivalent to unordered_map::operator[]:

If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

Upvotes: 1

Yuushi
Yuushi

Reputation: 26040

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;

Upvotes: 61

Related Questions