Manoj Rao bio photo

Manoj Rao

Your Average Common Man

Email Twitter Github

Imagine you are walking in the park on a beautiful day and suddenly … !

map:operator[] - Lookup or Insert

This is one of those quirks of the language C++:

map<int, ValueType> my_map;
if (my_map[42])
    // do something when key exists
    // do something when key does not exist

The above works counter intuitively since C++ creates a value object for the key 42 even when nothing is assigned since the object is created with a default constructor. So in, effect the predicate always evaluates to true even when clearly there is no such key in the map.

The right way to check for membership in map is to use map::find() or map::at() So the above code looks like:

if (my_map.find(42) != my_map.end())
    // do something when key exists
    // do something when key does not exist

Passing a key that’s not already mapped to map::at() throws an exception.

This might seem like a quirk of C++’s that needs fixing, but it is the same feature that allows the more intuitive functionality to exist in C++ in the first place:

map<int, ValueType> my_map;
my_map[42] = my_val_obj;

I’m making this a separate post as a note to self.

PS: Look up Item 24 on Scott Meyers’ Effective STL book for more details.

Bring Your Own Cause

If you think any info here has remotely helped you consider dropping a penny for this cause, just click me . You can visit Unfortunately, there are plenty of sad things happening all over the world, if you have a different cause or charity you'd rather support please do. And if you did make a donation, please drop a note to me (annotated) or leave a comment here (anonymous is OK!) and I will use that as motivation to write more useful content here.

If you like topics such as this then please consider subscribing to my podcast. I talk to some of the stalwarts in tech and ask them what their favorite productivity hacks are:

Available on iTunes Podcast

Visit Void Star Podcast’s page on iTunes Podcast Portal. Please Click ‘Subscribe’, leave a comment.

Get it iTunes