我目前有一个 std::map
将一个整数值存储到一个唯一的字符串标识符中,我确实使用该字符串进行查找.它主要做我想要的,除了它不跟踪插入顺序.因此,当我迭代地图以打印出值时,它们会根据字符串进行排序;但我希望它们按照(第一次)插入的顺序进行排序.
I currently have a std::map<std::string,int>
that stores an integer value to a unique string identifier, and I do look up with the string. It does mostly what I want, except that it does not keep track of the insertion order. So when I iterate 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.
我想过使用 vector
代替,但我需要查找字符串并将整数值增加大约 10,000,000 次,所以我不知道std::vector
是否会明显变慢.
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 std::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.它允许使用多个索引.在您的情况下,它可能如下所示:
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 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!