【发布时间】:2013-09-06 13:26:31
【问题描述】:
对于我的程序,我需要无序键。为了完成工作,我使用 std::unordered_map 容器。这是一个测试代码:
#include <iostream>
#include <unordered_map>
#include <string>
int main()
{
std::unordered_map<std::string, int> toto;
toto["Outlook"] = 454;
toto["Temperature"] = 4;
toto["Humidity"] = 554;
toto["Wind"] = 545454;
std::unordered_map<std::string, int>::iterator It = toto.begin();
std::cout << toto.size() << std::endl;
for (; It != toto.end(); ++It)
std::cout << (*It).first << std::endl;
getchar();
return (0);
}
在 Windows (Visual Studio 2012) 上,输出为:
Outlook
Temperature
Humidity
Wind
没错。未应用任何排序。
但在 Linux 上,输出如下:
Humidity
Outlook
Wind
Temperature
PS : 在 linux 上,我使用 -std::c++0x 和 -std=gnu++0x 编译我的程序,并且没有编译错误。
那么,同一个程序怎么可能有不同的行为呢? 提前感谢您的帮助!
【问题讨论】:
-
它是无序的。你为什么关心订单?
-
@chris 据我所知,unordered_map 使用哈希结果作为内部容器中元素的索引。
std::unordered_map迭代器是那个容器的迭代器,所以当你遍历 unordered_map 时,你实际上是遍历了那个内部容器。那么,不同的顺序意味着不同的哈希结果,或者不同的分配策略? -
@Manu343726:不同的实现。不同的月相。不同数量的山羊。订单未定义,仅此而已。没有什么需要了解的了。
-
所以你想知道为什么一个无序容器在使用不同操作系统上运行的不同编译器编译的不同实现上具有不同的顺序?
标签: c++ c++11 unordered-map