What is the difference in getting a value through aMap[key] and aMap.at(key) in C++?
Asked
Active
Viewed 1.1k times
24
Ruggero Turra
- 15,540
- 14
- 84
- 131
unj2
- 50,077
- 84
- 239
- 367
2 Answers
39
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.
Richard J. Ross III
- 54,187
- 24
- 128
- 194
25
In C++11 map::at exists (who knew?).
It throws an exception if the key doesn't exist, find returns aMap.end() if the element doesn't exist, and operator[] value-initializes a new value for the corresponding key if no value exists there.
Luchian Grigore
- 245,575
- 61
- 446
- 609
-
1@KerrekSB (since C++11) didn't know that though. – Luchian Grigore May 30 '12 at 17:50