在std::unordered_map中,如何迭代哈希值?

问题描述 投票:0回答:1

std::unordered_map
每个键都有哈希值。如何获取这些哈希值?

做什么用?评估哈希函数与数据集的相关性。我可以从外部生成哈希值,但我可能无法访问所使用的哈希函数。

c++ c++11 hash std unordered-map
1个回答
0
投票

“我可能无法访问所使用的哈希函数。”

可以访问所使用的哈希函数:

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

演示

“评估哈希函数与数据集的相关性。”

可以通过将不同的

std::unordered_map
类传递给其构造函数来为
Hash
提供自定义哈希函数。

© www.soinside.com 2019 - 2024. All rights reserved.