Windows和Linux上std :: unordered_map容器的不同行为 [英] Different behaviour with std::unordered_map container on Windows and Linux

查看:248
本文介绍了Windows和Linux上std :: unordered_map容器的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的程序,我需要具有无序的密钥。为了完成这项工作,我使用了std :: unordered_map容器。这是一个测试代码:

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

在Windows(Visual Studio 2012)上,输出为:

On windows (Visual Studio 2012) the ouput is :

Outlook
Temperature
Humidity
Wind

是正确的。没有应用任何排序。

It's correctly. None sort has been applied.

但是在Linux上,输出如下:

But on Linux the output is the following :

Humidity
Outlook
Wind
Temperature

PS :在linux上,我使用-std :: c ++ 0x和-std = gnu ++ 0x编译程序,并且没有编译错误。

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 !

推荐答案

unordered_map 通常(实际上总是读取)是使用哈希表实现的,默认情况下,哈希表使用 std :: hash 选择要在其中存储项目的存储桶。

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.

有很多不同的哈希函数,因此您看到的是Windows和Windows NT上 std :: hash 的两个不同标准库实现。 Linux使用两种不同的哈希函数-产生不同的哈希码-依次产生不同的存储区放置,并因此在迭代时产生不同的顺序。

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.

这篇关于Windows和Linux上std :: unordered_map容器的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆