繁体   English   中英

std :: unordered映射不按哈希值的升序存储条目

[英]std::unordered map does not store entries in increasing order of hash values

我正在使用Visual Studio 2010,并且正在使用C ++ 11功能std :: unordered_map :: hash_function()来打印为每个键字符串计算得出的哈希值。

但是,我发现在内部条目是按随机顺序存储的,而不是按哈希值的升序存储。

在下面的示例中,Dad计算到最低的哈希值,并且应该是my_family_height_map的开始条目,但不是。 并且开始的元素是sis对,其计算得出的哈希值比Dad高。

凸轮有人解释为什么我看到这种奇怪的行为?

// unorderedmap_usage.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unordered_map>
#include <string>
#include <iostream>

int main()
{
    typedef std::unordered_map<std::string, double> height_map;
    height_map my_family_height_map;

    my_family_height_map["Dad"] = 5.10;
    my_family_height_map["Mom"] = 5.3;
    my_family_height_map["Sis"] = 5.3;
    my_family_height_map["Zach"] = 6.2;

    height_map::const_iterator c_it;

    // Print everything in the map
    for(c_it = my_family_height_map.begin(); c_it!= my_family_height_map.end(); ++c_it)
    {
        std::cout << "Hash:" << hasher_func(c_it->first) << "  Person is : " << c_it->first << " - height is " << c_it->second << "\n";
    }
}

O / P:
哈希:572570820人是:Sis-身高是5.3
哈希:306541572人是:爸爸-身高是5.1
哈希:1076885014人是:妈妈-身高是5.3
哈希:2613037907人是:Zach-身高是6.2
按任意键继续 。

顾名思义, 无序映射是无序的 规范中没有要求说必须按照散列增加的顺序对条目进行迭代。 或减少哈希值。 或任何东西,这就是为什么它被称为“无序”的原因。 1个

如果需要技术细节,则必须将哈希值转换为bin索引。 根据哈希表中bin的数量,通过某种截断/包装/等算法完成此操作。 这就是为什么它是无序的。 因为迭代的顺序通常是bin的顺序,所以不必与哈希的顺序匹配。

1从技术上讲,它被称为“无序”,因为许多C ++标准库实现已经带有称为hash_map/set/etc类型。 而且委员会不想与他们重叠。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM