Windows 和 Linux 上的 std::unordered_map 容器的不同行为
Different behaviour with std::unordered_map container on Windows and Linux
对于我的程序,我需要有无序键。为了完成工作,我使用 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) - 容器是无序的。没有人保证项目的顺序是什么,而且是真实的 - 每个实现都有不同的顺序。
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C/C++ Linux 上的多线程服务器/客户端崩溃
- Linux 上的黑屏,但 Windows 上不是
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- 使用eBPF拦截Linux上的所有传出/传入流量
- 如何在 Oracle Linux 上的 Eclipse 中编译和链接 boost 库
- C++ Linux 上的插件 ABI 问题
- 如何在 Linux 上的 C/C++ 中使用 ipv6 udp 套接字进行多播?
- Linux 上的 .NET Core - 元帅结构
- Linux上的PTHREAD_CANCEL()导致异常/Coredump,为什么
- 该命令在QProcess中启动,不会返回Linux上的响应
- 在RHEL 7上编译MySqlClient,并在RHEL 6上运行(Linux上的G )
- 跨平台套接字发送,Linux 上的缓冲区常量无效* Windows上的常量字符*,最佳处理方式
- Linux 上的键码表
- 如何检测 CDRom 是否是 Linux 上的 DVD
- Linux 上的 FreeImage 返回 -1 格式
- 在 Linux 上的 Visual Studio 中链接两个项目
- QT 5.8(Ubuntu 16.04)Linux上的应用程序部署
- 除了 Linux 上的源代码和编译 (GCC) 之外,有没有办法在 Windows 中托管 IDE
- 写入 Linux 上的共享内存时出现周期性延迟峰值