What is the difference in getting a value through aMap[key]
and aMap.at(key)
in C++?
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”.
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."
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.
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).
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.
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