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?
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.
For the unordered_map + map , it takes 70 ms for unordered_map insertion and 80 ms for map insertion. So the hybrid implementation is 50 ms faster.
The time complexity of map operations is O(log n) while for unordered_map, it is O(1) on average.
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
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