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

时间:2013-09-06 13:26:31

标签: c++ c++11 unordered-map

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

那么,如何在同一个程序中使用不同的行为呢? 在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

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

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

如果您不明白这意味着什么,我会花一些时间研究hash table data structure。在编程的许多方面,散列是一个非常酷且有用的数学工具。

答案 1 :(得分:4)

正如名称(unordered_map)所暗示的那样 - 容器是无序的。没有人保证物品的顺序和真实性 - 每个实施都有不同的顺序。