Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 954
user997112 Avatar asked Oct 05 '13 12:10

user997112


People also ask

How do I add elements to an unordered map?

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.

What is faster than unordered_map?

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.

What is the time complexity of unordered_map?

The time complexity of map operations is O(log n) while for unordered_map, it is O(1) on average.


3 Answers

You just do (for map and unordered_map)

mydict[key]=value;
like image 128
Joe Avatar answered Oct 16 '22 13:10

Joe


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.

like image 44
Daniel Frey Avatar answered Oct 16 '22 13:10

Daniel Frey


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

like image 9
htmlboss Avatar answered Oct 16 '22 13:10

htmlboss