What is the use of emplace_hint in map?

后端 未结 2 914
再見小時候
再見小時候 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 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.

提交回复
热议问题