跟踪插入顺序的std :: map? [英] A std::map that keep track of the order of insertion?
问题描述
我目前有一个 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>>
,但是我需要看上升字符串,并增加大约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或者还有另一个更适合我需要的标准容器?
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 一>。它允许使用多个索引。
在你的情况下,它可能如下所示:
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屋!