Suppose you want to insert an element into a card only if the key is not already specified. Of course, you can just call insert , but suppose the operation is expensive or irreversible (for example, moving from an object that cannot be copied).
In this situation, you need to separate the search from the insert. Where the hint appears, combined with lower_bound :
auto it = m.lower_bound(key); if (it != m.end() && it->first == key) { // key already exists } else { m.insert(it, std::make_pair(key, compute_expensively())); // or: m.emplace_hint(it, key, compute_expensively()); }
The trick is that lower_bound returns an iterator where the key would be if it were on the map, regardless of whether it is really there. The time complexity of the intended insert is constant if the prompt is correct.
It makes no sense to use the intended insert with the wrong iterator (i.e. the one that was not obtained as the lower bound for the given key).
Note that the intended insertion only works for ordered associative containers. Unordered containers also offer these overloads, but they do not work, since there is no way to get useful advice for unordered containers.
Kerrek SB
source share