Later, I found the following code:
1 2 3 4 5 6 |
auto p = map.find(key); if (p != map.end()) { throw std::runtime_error(...); } prepare(value); map[key] = value; |
We cannot adopt the solution of the previous post, because the call to prepare is conditioned by the absence of the key in the map and precedes the insertion of value in the map. Moreover, in case of exception thrown by prepare, the value will not be inserted in the map, and hence prepare cannot be postponed after the insertion. In order to respect the flow order without paying twice the cost of finding the position of the key in the map, one should adopt the solution described by Scott Meyer in the Item 24 of Effective STL.
1 2 3 4 5 6 |
auto p = map.lower_bound(key); if (p != map.end() && p->first == key) { throw std::runtime_error(...); } prepare(value); map.insert(p, std::make_pair(key, value)); |
With C++11, the last statement would be better:
1 |
map.emplace_hint(p, key, value); |