gpt4 book ai didi

c++对象的映射顺序

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:02 24 4
gpt4 key购买 nike

我想知道为什么我的输出看起来像这样:

This : 1
a : 4
is : 2
just : 3
test : 5

当我的代码如下所示时:

map<string, int> wordCount;
wordCount["This"] = 1;
wordCount["is"] = 2;
wordCount["just"] = 3;
wordCount["a"] = 4;
wordCount["test"] = 5;
for (map<string, int>::iterator it = wordCount.begin();
it != wordCount.end(); it++) {
cout << it->first << " : " << it->second << endl;
}

我的问题是, map 是否以随机顺序存储对象?

最佳答案

map 按排序顺序存储内容。原因"This""a" 之前是那个'T''a' 之前在大多数(如果不是所有字符集)中,所以 'T' < 'a'因此 "This""a" 之前因为不考虑字符串的长度。

如果你改变Thisthis那么你会得到

a : 4
is : 2
just : 3
test : 5
this : 1

Live Example

关于c++对象的映射顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com