What is the quickest way of inserting/updating std::unordered_map elements without using an if?
You just do (for map
and unordered_map
)
mydict[key]=value;
I think it might be fastest like this:
auto it = my_dict.find(key);
if( it != my_dict.end() ) {
it->second = value;
}
else {
my_dict.insert(std::make_pair(key,value));
}
that way you don't modify the structure of the unordered_map
if the key
already exists and you only have one lookup.
Another option in case you don't need/access value
afterwards:
my_dict[key] = std::move(value);
This might be better in cases when the assignment of value
is expensive and benefits from move-semantics.
To update for C++17, you can use:
std::unordered_map::insert_or_assign()
http://en.cppreference.com/w/cpp/container/unordered_map/insert_or_assign