I know how to use std::unordered_map::emplace
, but how do I use emplace_hint
? Neither cplusplus nor cppreference provide a set of examples that illustrate how we might know where to put the element.
Can anyone provide some information on this or give some examples / illustrations of when we might know where the emplaced element should go?
What could an unordered_map
potentially do with the hint? Well, if the iterator addresses an element with the same key as the element that emplace_hint
has been asked to insert, then it can fail quickly - just a key comparison without any hashing or groping through any list of hash-colliding elements at that bucket. But if the key doesn't match, then the hint is otherwise useless because any other key - no matter how "close" in value - should (probabilistically) be at a completely unrelated bucket (given what's normally considered a "good" hash function), so time would have been wasted on a key comparison only to have to start over as if it were a normal emplace
.
This might be useful when you're inserting pre-sorted-by-key elements, aiming to remove lots of duplicates in the process, but the key is so huge it's easier to keep an iterator to the just-inserted element than a copy of the key, or perhaps the hash function is particularly slow.
Another benefit of unordered_map::emplace_hint
is better API compatibility with map::emplace_hint
, so code can switch the container type and have the emplace_hint
s not break the compile, though they might end up slower than if the code were switched to emplace()
as the close-but-different-key hints that help with a map
may be useless with an unordered_map
.
来源:https://stackoverflow.com/questions/22800405/when-do-you-use-stdunordered-mapemplace-hint