使用 boost multi_index_container 来保留插入顺序

发布于 2024-09-09 16:23:23 字数 386 浏览 2 评论 0 原文

我最初开始使用 std::multimap 来存储具有相同键的多个值,但后来我发现它不能保留具有相同键的值之间的插入顺序。 这个答案声称可以通过boost::multi_index::multi_index_container,但没有给出示例。浏览文档,没有该用法的示例,而且我无法弄清楚您应该如何使用这个东西。我本来以为很少使用的 boost 库会提供糟糕的文档,但这是最重要的。任何人都可以向我指出一个教程或示例,以显示它按照我想要的方式使用,或者甚至可以自己提供一个示例吗?

I initially started out using a std::multimap to store many values with the same key, but then I discovered that it doesn't preserve the insertion order among values with the same key. This answer claims it can be done with boost::multi_index::multi_index_container, but gives no example. Looking through the docs, there are no examples of that usage, and I can't make heads or tails of how you're supposed to use this thing. I have come to expect poor documentation from the lesser-used boost libraries, but this takes the cake. Can anyone point me to a tutorial or example that shows it used the way I want, or perhaps even provide an example themselves?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

下壹個目標 2024-09-16 16:23:23

您可以通过使用 boost::multi_index 和两个索引来实现此目的:ordered_non_unique(允许具有相同键的值)和 random_access(这将保持插入顺序) 。

struct some {
  long key;
  int data;
  int more_data;
  // etc.  
};

typedef multi_index_container<
  some, 
  indexed_by<    
    random_access<>,  // keep insertion order
    ordered_non_unique< member<some, long, &some::key> >
  > 
> some_mic_t;

You could achieve this by using boost::multi_index with two indices: ordered_non_unique(which allows values with the same key) and random_access(which will keep the insertion order).

struct some {
  long key;
  int data;
  int more_data;
  // etc.  
};

typedef multi_index_container<
  some, 
  indexed_by<    
    random_access<>,  // keep insertion order
    ordered_non_unique< member<some, long, &some::key> >
  > 
> some_mic_t;
情话墙 2024-09-16 16:23:23

@Kirill:很好

map<int, vector<string> >

map<int, list<string> >

的答案。我怀疑 Boost 的 random_access 可能非常慢,因为它会强制所有键的所有字符串都维护在一个连续的结构中。而提问者只是希望在每个键的映射值集中保留顺序。

How about a

map<int, vector<string> >

or

map<int, list<string> >

@Kirill: Good answer. I suspect Boost's random_access can be quite slow, as it will force all strings for all keys to be maintained in a single contiguous structure. Whereas the questioner simply wants order to be preserved within each key's set of mapped values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文