简体   繁体   中英

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

I am using Visual studio 2010 and I am using the C++ 11 feature std::unordered_map::hash_function() to print the hash values that get computed for each of the key strings.

However I find that internally the entries are stored in random order and not in increasing order of the hashvalues.

In the example below, Dad computes to the lowest hash value and should be the beginning entry of the my_family_height_map, but it is not. And the beginning element is the sis pair which computes to a higher hash value than the Dad.

Cam someone explain why I am seeing this weird behavior?

// 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:
Hash:572570820 Person is : Sis - height is 5.3
Hash:306541572 Person is : Dad - height is 5.1
Hash:1076885014 Person is : Mom - height is 5.3
Hash:2613037907 Person is : Zach - height is 6.2
Press any key to continue . . .

Unordered map is, as the name suggests, unordered . There is no requirement in the spec that says that entries must be iterated over in order of increasing hashes. Or decreasing hashes. Or anything at all, which is why it's called "unordered". 1

If you want the technical details, the hashes have to be turned into bin indices. This is done via some truncation/wrapping/etc algorithm, based on the number of bins in the hash table. That's why it's unordered; because the order of iteration is typically the order of bins, which does not have to match with the ordering of hashes.

1 Technically, it's called "unordered" because many C++ standard library implementations already shipped with types called hash_map/set/etc . And the committee didn't want to overlap with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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