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

别等时光非礼了梦想. 提交于 2020-01-05 08:39:58

问题


For my program I need to have unordered key. To do the job done I use std::unordered_map container. Here's a test code :

#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);
}

On windows (Visual Studio 2012) the ouput is :

Outlook
Temperature
Humidity
Wind

It's correctly. None sort has been applied.

But on Linux the output is the following :

Humidity
Outlook
Wind
Temperature

PS : On linux I compile my program with -std::c++0x and -std=gnu++0x and there is no compilation error.

So, how is possible to have a different behaviour with the same program ? Thanks in advance for your help !


回答1:


unordered_map is usually (read practically always) implemented with a hash table, which by default uses std::hash to select which bucket to place an item in.

There are many different hash functions, so what you are seeing is that the two different standard libraries implementation of std::hash on Windows and Linux use two different hash functions - which produce different hash codes - that in turn produce different bucket placement, and hence different orderings when iterated.

I would spend some time studying the hash table data structure in general if you don't understand what this means. Hashing is a really cool and useful mathematical tool in many aspects of programming.




回答2:


As the name (unordered_map) implies - the container is unordered. No one makes any guarantees as to what the order of the items will be and truly - each implementation has a different order.



来源:https://stackoverflow.com/questions/18658987/different-behaviour-with-stdunordered-map-container-on-windows-and-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!