What is the quickest way of inserting/updating std::unordered_map elements without using an if?

user997112 picture user997112 · Oct 5, 2013 · Viewed 58.8k times · Source

I currently have lots of code which looks like this:

std::unordered_map<int,int> my_dict;
.
.
.
// If the key does exist in the dictionary
if(my_dict.count(key) == 1){
    my_dict[key] = value;
}

// If its a new key
else{
    my_dict.insert(std::make_pair(key,value));
}

Is there any way I can speed this up by just overwriting the value every time?

Answer

Joe picture Joe · Oct 5, 2013

You just do (for map and unordered_map)

mydict[key]=value;