how does the stl's multimap insert respect orderings?

后端 未结 7 2208
灰色年华
灰色年华 2020-12-03 21:15

I have some data which come with a integer index. I am continuous generating new data which needs to added to the collection of data I have, sorted by that index, at the sa

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 21:44

    If I got you right - you need the data sorted by some key. Whenever you insert 2 things with the same key, you need to retrieve them in the order of insertion.

    If that's the case, then you have to take a look at the implementation of your multimap. Depending on how it handles the case of multiple insertions with the same key it may or may not have this guarantee. I guess the standard does not offer this kind of guarantee, since it would limit the implementation for a very special case.

    Another approach is to go for a Map (not Multi) and create a compound key. The key consists of the normal key you choose and an alway increasing counter. On comparison, with equal keys, the insertion number makes the key unique. This way you force unique keys and the order on equal "normal" keys (I hope this was understandable).

    I guess the last approach is the easiest to implement.


    Option: (not preferable)

    You can always go for a self-made datastructure with this guarantee. I'd go for a Tree (Red-Black or AVL for example) with a vector to hold the inserted data. On iteration you have to find the node, go to the vector and iterate on it's content. Whenever you finish with the vector, you continue with the next node.

提交回复
热议问题