Is there any difference between the following commands from std::unordered_map

Viewed 294

For inserting a key-value pair into an unordered map, e.g., std::unordered_pair<int,int> map1, can we do it in any of these two ways:

map1[2]=5;
map1.insert({2,5});

Is there any difference between using std_unordered_insert or operator[]?

And if I want to find the mapped value for a given key, can I use either of the following:

mappedVal = map1.at(2);
mappedVal = map1[2];

Again, any difference between using std::unordered_map::at or operator[]?

2 Answers

map1[2]=5;

If an entry with key 2 exists, set that entry's value to 5. Otherwise, create a new entry with key 2 and value 5.


map1.insert({2,5});

If no entry with key 2 exists, create a new entry with key 2 and value 5. Otherwise, do nothing.


mappedVal = map1.at(2);

If an entry with key 2 exists, assign its value to mappedVal. Otherwise, throw an out_of_range exception.


mappedVal = map1[2];

If an entry with key 2 exists, assign its value to mappedVal. Otherwise, create an entry for 2 using the default value and assign that default value to mappedVal.


For lookups, I usually use unordered_map::find() rather than at() or operator [] () (unless I know that there is an entry for the given key).

In contrast to operator[], at() will throw a std::out_of_range exception if the key doesn't exist. operator[] will create the key instead.

Related