Avoid finding twice the same key in the map (part 1)

This is unfortunate, but I regularly still see the following piece of code:

This code is suboptimal and is premature pessimization. Indeed, both the find operation in line (1) and the operator[] called in line (2) perform in O(log N). It is possible to get the same net effect with only one O(log N) operation. The correct version is the following:

We’ll see in a next post that this solution does not work in all situations.

This entry was posted in C++, C++11, STL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *