Windows 和 Linux 上的 std::unordered_map 容器的不同行为

Different behaviour with std::unordered_map container on Windows and Linux

本文关键字:Linux 上的 std Windows unordered map      更新时间:2023-10-16

对于我的程序,我需要有无序键。为了完成工作,我使用 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 编译我的程序,并且没有编译错误。

那么,如何对同一个程序有不同的行为呢?提前感谢您的帮助!

unordered_map通常(几乎总是读取)使用哈希表实现,默认情况下,哈希表使用std::hash来选择要放置项目的存储桶。

有许多不同的哈希函数,所以你看到的是Windows和Linux上std::hash的两个不同的标准库实现使用两个不同的哈希函数 - 产生不同的哈希代码 - 反过来产生不同的桶放置,因此迭代时有不同的排序。

如果您不明白哈希表数据结构的含义,我会花一些时间研究它。 哈希在编程的许多方面都是一个非常酷和有用的数学工具。

顾名思义 (unordered_map) - 容器是无序的。没有人保证项目的顺序是什么,而且是真实的 - 每个实现都有不同的顺序。