What is the use of emplace_hint in map?

后端 未结 2 911
再見小時候
再見小時候 2021-02-01 06:05

I understand that map::emplace_hint is used to place a key,value pair at a specified place in the map but in the end the map gets sorted so what is the point of placing it in a

相关标签:
2条回答
  • 2021-02-01 06:52

    Suppose you want to insert an element into a map only if the key isn't present yet. You could of course just call insert, but suppose further that the operation is expensive or irreversible (e.g. moving from a non-copyable object).

    In that situation, you need to separate the lookup from the insertion. That's where the hint comes in, in conjunction 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 the iterator where the key would be if it were in the map, regardless of whether it actually is there. The time complexity of the hinted insertion is constant if the hint is correct.

    There's no point using the hinted insertion with an incorrect iterator (i.e. one that wasn't obtained as the lower bound for the given key).

    Note that hinted insertion only works for ordered associative containers. The unordered containers also offer those overloads, but they have no effect, since there is no way to obtain a useful hint for unordered containers.

    0 讨论(0)
  • 2021-02-01 07:00

    I understand that map::emplace_hint is used to place a key,value pair at a specified place in the map

    No, it isn't.

    As you say, you cannot control the position of elements yourself. The map decides that.

    This hint is to tell the compiler where you think the map will decide to put it, so that the map doesn't have to spend quite as long figuring that out for itself.

    For example, if you already know (because it's your program!) that some new element is definitely going to end up at the "start" of the map, then you can pass this knowledge onto the container. It then only needs to check that you're right, instead of scanning through the whole tree to eventually come to that conclusion itself.

    If your hint is wrong, that doesn't change anything about where the element ends up, but you're giving the map more work to do.

    0 讨论(0)
提交回复
热议问题