This is unfortunate, but I regularly still see the following piece of code:
1 2 3 4 5 |
auto p = map.find(key); // (1) if (p != map.end()) { throw std::runtime_error(...); } map[key] = value; // (2) |
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:
1 2 3 4 |
auto result = map.insert(std::make_pair(key, value)); if (!result.first) { throw std::runtime_error(...); } |
We’ll see in a next post that this solution does not work in all situations.