A std::map that keep track of the order of insertion?(跟踪插入顺序的 std::map ?)
问题描述
我目前有一个 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 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:跟踪插入顺序的 std::map ?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
