Dark Secrets of std::map [ ] operator

Dark Secrets of std::map [ ] operator

While trying to read the value corresponding to key, If we accidentally pass a key which doesn't exist in the map using [ ] operator, , then the element is silently inserted into map.

Let us see this in action, Initialize a simple harmless map with 3 key-value pairs, `std::map city {{1, london}, { 2, paris}, {3, vienna}};

Now, let us access an element from with key 2,

std::cout<<city[2]<<endl;         // paris
std::cout<<city.size();           // 3

Now for black magic, try and access an index which didn't exist in the map and check the size of map,

std::cout<<city[4]<<endl;         // Access a key which doesn't exist
std::cout<<city.size();           // 4

Alas, silently an element is inserted to map with the supplied key , note that, this element didn't exist in the map at the first place. This will cause all sorts of unintended consequences

image.png

I know, I know, But this is nothing but the truth, only the truth.
So, how do we protect ourselves from these dark forces of std::map,

Recommendation:
When trying to read values, use at method provided by std::map instead of [ ] operator