C++添加顺序的字典/地图
我想要有类似于地图的东西,但在迭代时我希望它们的顺序与添加的顺序相同。
示例
map.insert("one", 1);
map.insert("two", 2);
map.insert("three", 3);
在迭代时,我希望项目类似于“一”、“二”、“三”。默认情况下,地图不提供此添加顺序。如何按照我添加的方式获取地图元素?我想要保留插入顺序
的任何内容都可以,或者其他替代建议也可以。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个 std::map 跟踪顺序插入?
这是重复的(感谢尼尔·巴特沃斯)
您可以使用具有与之平行的排序结构的映射。
A std::map that keep track of the order of insertion?
this is a duplicate (thanks to neil butterworth)
You could use a map with a sorted structure parallel to it.
Boost mult iindex 使得容器能够以多种不同的顺序进行迭代。
http://www.boost.org/doc/ libs/1_42_0/libs/multi_index/doc/index.html
稍微修改的示例:
Boost mult iindex makes it possible to have a container which can be iterated over in several different orders.
http://www.boost.org/doc/libs/1_42_0/libs/multi_index/doc/index.html
Slightly modified example:
实际上, 。 > 或
std::map
默认情况下使用std::less
对键进行排序,其中T
是键的类型。如果您不希望按键对元素排序,则应该使用 std::liststd::vector >
-- 其中K
是您的键类型,V
是您的值类型,然后使用push_back
添加元素到列表/向量的末尾。Actually
std::map
by default sorts your keys usingstd::less<T>
whereT
is your key's type. If you don't want the elements sorted by key, you should be using anstd::list<std::pair<K,V> >
or anstd::vector<std::pair<K,V> >
-- whereK
is your key type, andV
is your value type, and then usingpush_back
to add elements to the end of the list/vector.