std::map and the 2 evils

The task: store pairs of keys and objects in a map. Sounds simple? Well. std::map offers several ways of accessing its members:

operator[key]
at(key)
find(key)

That all sounds good as long as the key exists in the map. If not, it can get tricky: the operator[] inserts the key and a default constructed element, which often might be undesired, and we also cannot use it with const.

And the at() method? Throws an exception. There is a chance you don’t want neither of them.

What we still can try is getting an iterator using find():

auto it = myMap.find(9);

The iterator needs to be checked to not be end(), in case the element doesn’t exist in the map.

The value type of a map is std::pair<const Key, T>, so we can get the key and element from the iterator like so:

auto key = it->first;
auto value = it->second;