stl的multimap插件如何尊重顺序? [英] how does the stl's multimap insert respect orderings?

查看:199
本文介绍了stl的multimap插件如何尊重顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据与整数索引。我连续生成新的数据,需要添加到我收集的数据,按该索引排序,同时我想轻松地能够去开始的数据和迭代通过它。这听起来像std :: multimap只是我需要的。

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 same time I want to easily be able to go the start of the data and iterate through it. This sounds like std::multimap is just what I need.

但是,我还需要相同的索引的数据保持在它的插入顺序,

However, I also need data with the same index to be kept in the order in which it was inserted, in this case meaning that when I iterate through the data I get to the earlier data before the later data.

多重图是否可以做到这一点?

Does multimap do this?

我没有找到任何保证,这是这种情况。在sgi手册中,我没有看到任何提到是否。我试过gcc 4.3.4实现,它似乎是一些有限的测试用例,但当然我想知道是否标准要求这一点,我可以依靠这个事实。

I haven't found any guarantees that this is the case. In the sgi manual, I didn't see any mention of whether. I tried it on gcc 4.3.4 implementation and it seemed to be true for some limited test cases, but of course I was wondering whether the standard demands this and I can rely on this fact.

编辑:为了更清楚地回答一些答案,我想要的数据首先排序(非唯一)索引和第二个插入时间。

To be clearer in response to some of the answers, I wanted the data sorted first by (non-unique) index and second by insertion time. I had hoped that maybe the second part came for free with multimap, but it seems like it doesn't.

推荐答案

除非我没有提供任何保证。

Unless I've missed something, the standard doesn't provide any such guarantee.

最明显的解决方法是将序列号作为辅助键。例如,在您的类中包含静态unsigned long,并且每次在多图中创建要插入的对象时,将其当前值放入您的对象中,然后递增。在对象的比较函数中,如果当前用作键的数据比较相等,则使用该计数器作为排序的决定因素。请注意,在这种情况下,每个键都是唯一的,因此您可以使用地图而不是多图。

The most obvious workaround would be to include a sequence number as a secondary key. For example, in your class include a static unsigned long, and each time you create an object to insert in the multimap, put its current value into your object, and increment it. In your object's comparison function, use that counter as the deciding factor for ordering if the data you're currently using as the key compares equal. Note that in this case, each key will be unique, so you can use a map instead of a multimap.

这篇关于stl的multimap插件如何尊重顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆