一个std :: map跟踪插入的顺序? [英] A std::map that keep track of the order of insertion?

查看:544
本文介绍了一个std :: map跟踪插入的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个 std :: map< std :: string,int> ,它将整数值存储到唯一的字符串标识符,我会查找该字符串。它主要是我想要的,除了它不跟踪插入顺序。因此,当我迭代地图打印出值时,它们根据字符串进行排序;但我想要他们根据(第一)插入的顺序排序。

I currently have a std::map<std::string,int> that stores an integer value to an unique string identifier, and I do look up with the string. It does mostly what I want, except for that it does not keep track of the insertion order. So when I iterate the the map to print out the values, they are sorted according to the string; but I want them to be sorted according to the order of (first) insertion.

我想到使用向量< pair< string,int>> up字符串和增加整数值大约10,000,000倍,所以我不知道一个向量是否会显着更慢。

I thought about using a vector<pair<string,int>> instead, but I need to look up the string and increment the integer values about 10,000,000 times, so I don't know whether a vector will be significantly slower.

有没有办法使用std :: map或者有另一个std容器更适合我的需要吗?

Is there a way to use std::map or is there another std container that better suits my need?

[我在GCC 3.4,我在std :: map中可能不超过50对值]。

[I'm on GCC 3.4, and I have probably no more than 50 pairs of values in my std::map].

推荐答案

如果你在std :: map中只有50个值,你可以在打印出来之前将它们复制到std :: vector,并使用适当的函子通过std :: sort进行排序。

If you have only 50 values in std::map you could copy them to std::vector before printing out and sort via std::sort using appropriate functor.

您也可以使用 boost :: multi_index 。它允许使用几个索引。
在你的case你可能看起来像下面的:

Or you could use boost::multi_index. It allows to use several indexes. In your case it could look like the following:

struct value_t {
      string s;
      int    i;
};
struct string_tag {};
typedef multi_index_container<
    value_t,
    indexed_by<
        random_access<>, // this index represents insertion order
        hashed_unique< tag<string_tag>, member<value_t, string, &value_t::s> >
    >
> values_t;

这篇关于一个std :: map跟踪插入的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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