简体   繁体   中英

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

For inserting a key-value pair into an unordered map, eg, 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[] ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM