c++ 在std::unordered_map中,如何遍历散列?

aydmsdu9  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(109)

std::unordered_map中的每个键都有一个hash-value。如何获得这些hash-value?
干什么?为了评估哈希函数与数据集的相关性,我可以从外部生成哈希函数,但我可能无法访问所使用的哈希函数。

yyhrrdl8

yyhrrdl81#

  • “我可能无法访问使用的哈希函数。"*

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

#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

  • “评估散列函数与数据集的相关性。"*

可以通过向Hash的构造函数传递不同的Hash类来为std::unordered_map提供自定义哈希函数。

相关问题