In std::unordered_map, how to iterate over hashes?

80 Views Asked by At

The std::unordered_map has hash-value for each key. What is the way to obtain those hash values?

What for? To evaluate relevance of a hash function to the data set. I could just generate hashes from outside, but I might not have access to the hash function used.

1

There are 1 best solutions below

0
Amit On

"I might not have access to the hash function used."

There is access to the hash function used:

#include <unordered_map>
#include <iostream>

int main()
{
    const std::unordered_map<int, int> my_map = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
    const auto hasher{ my_map.hash_function() };

    for (const auto& [key, value] : my_map) { // Structured bindings were introduced in C++17

        const auto hash_value = hasher(key);

        std::cout << "(h: " << hash_value << ", k: " << key << ", v: " << value << ")   ";
    }

    std::cout << std::endl;
}

Demo

"To evaluate relevance of a hash function to the data set."

It is possible to provide a custom hash function for std::unordered_map by passing a different Hash class to its constructor.