Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between map[] and map.at in C++?

Tags:

What is the difference in getting a value through aMap[key] and aMap.at(key) in C++?

like image 959
unj2 Avatar asked May 30 '12 17:05

unj2


People also ask

What does map at return?

map::at() at() function is used to reference the element mapped to the key value given as the parameter to the function. For example, if we have a string “hi” mapped to an integer 1, then passing the integer 1 as the parameter of at() function will return the string “hi”.

Which is faster map or Unordered_map?

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order."

What is difference between set vector and map?

The difference is set is used to store only keys while map is used to store key value pairs. For example consider in the problem of printing sorted distinct elements, we use set as there is value needed for a key. While if we change the problem to print frequencies of distinct sorted elements, we use map.

Is map already sorted?

No. It will iterate based on the sorted order, not the order that you inserted elements. In the case of std::string , it sorts in lexicographic order (alphabetic order).


1 Answers

If you access a key using the indexing operator [] that is not currently a part of a map, then it automatically adds a key for you. This is a huge caveat, and take this into consideration. For this reason, I prefer using the indexing operator [] for setting, and .find() / .at() for lookup.

Another advantage of using .at() over [] is the fact that it can operate on a const std::map, whereas [] won't.

like image 150
Richard J. Ross III Avatar answered Oct 05 '22 10:10

Richard J. Ross III