c++ std::map<string,string> 是有序的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11274978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:00:01  来源:igfitidea点击:

Are c++ std::map<string,string> ordered?

c++

提问by CodingHero

are STL maps ordered?

STL 映射是否已订购?

Specifically I need to know if std::map is ordered. So if I iterate over it, it will iterate with the first insert string first.

具体来说,我需要知道是否订购了 std::map。因此,如果我对其进行迭代,它将首先使用第一个插入字符串进行迭代。

So will the below iterate A, C then B consistantly?

那么下面的内容会一致地迭代 A, C 然后 B 吗?

std::map<string,string> str_map;

str_map.insert(std::make_pair("A","Data"));
str_map.insert(std::make_pair("C","Data"));
str_map.insert(std::make_pair("B","Data"));

回答by Oliver Charlesworth

are STL maps ordered?

STL 映射是否已订购?

Yes, a std::map<K,V>is ordered based on the key, K, using std::less<K>to compare objects, by default.

是的,默认情况下, astd::map<K,V>是基于键排序的Kstd::less<K>用于比较对象。

So if I iterate over it, it will iterate with the first insert string first?

所以如果我迭代它,它会先迭代第一个插入字符串?

No. It will iterate based on the sorted order, not the order that you inserted elements. In the case of std::string, it sorts in lexicographic order (alphabetic order).

不。它将根据排序顺序进行迭代,而不是您插入元素的顺序。在 的情况下std::string,它按字典顺序(字母顺序)排序。

If you want to iterate based on the insertion order, you're better off using a sequence container, such as a std::vectoror a std::list.

如果要根据插入顺序进行迭代,最好使用序列容器,例如 astd::vector或 a std::list

回答by sepp2k

std::maps are sorted using either the given type's operator<or using a custom comparison function/functor if one is supplied as an argument to the constructor.

std::maps 使用给定类型operator<或使用自定义比较函数/函子(如果一个作为参数提供给构造函数)进行排序。

So no, when you iterate over the map, the first item you get won't be the one you inserted first - it will be the one that comes first alphabetically.

所以不,当您遍历地图时,您获得的第一个项目不会是您首先插入的项目 - 它将是按字母顺序排列的第一个项目。

Of course for your sample code that doesn't make a difference because "A" is the first key you inserted and also the first one alphabetically.

当然,对于您的示例代码没有任何区别,因为“A”是您插入的第一个键,也是按字母顺序排列的第一个键。