【问题标题】:How to write a custom hash_function for std::unordered_map<T> in cpp?如何在 cpp 中为 std::unordered_map<T> 编写自定义哈希函数?
【发布时间】:2021-05-04 17:48:09
【问题描述】:

我想为 std::unordered_map 编写自己的 Hash_function,而不是使用默认的。 我可以在许多网站上找到 unordered_map::hash_function()。 但是使用这个我只能得到生成的哈希值,使用类似这样的东西:

/*Sample map of strings*/

unordered_map<string, string> sample;

// inserts key and elements
sample.insert({ "Tom", "MNNIT" });
sample.insert({ "Kate", "MNNIT" });

unordered_map<string, string>::hasher foo
    = sample.hash_function();

cout << foo("Tom") << endl;

但是我怎样才能拥有更多的控制权并创建我自己的散列函数版本呢?因此,例如,让我们说键“Tom”,我希望哈希值为 100。

【问题讨论】:

标签: c++ std


【解决方案1】:

std::unordered_map 模板来自默认为 std::hash&lt;Key&gt;Hasher。您可以将变量更改为std::unordered_map&lt;string, string, CustomHasher&gt;。然后unordered_map 将默认构造一个CustomHasher(如果您不能默认构造散列对象,它也可以在构造函数中传递)。

自定义哈希器需要提供如下调用运算符:

struct CustomHasher
{
    // noexcept is recommended, but not required
    std::size_t operator()(const std::string& s) const /*noexcept*/
    {
        return /*hash computation here*/;
    }
};

注意:编写依赖于 unordered_map 中存储的哈希值的代码通常是一个糟糕的设计。有一些需要自定义哈希函数的有效用例,例如当您可以利用某些特定于数据的信息来生成更好的哈希时,但这种情况很少见。

【讨论】:

  • 请注意:不一定是noexcept
  • @Evg 好点,将其从示例中删除。
  • 我不是故意要删除noexcept。拥有noexcept 哈希器是一件好事,但该标准并未强制要求不抛出自定义哈希器。例如,libstdc++ 对noexcept 哈希器进行了一些内部优化(如果哈希器不是noexcept,那么哈希码必须存储在节点中,请参阅github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/…)。在那个特定的实现中 noexcept 单独不足以触发优化(哈希器也应该是“快速的”),但在其他一些实现中它可能很重要。
猜你喜欢
  • 1970-01-01
  • 2021-10-09
  • 2018-06-07
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 2020-08-23
  • 2016-05-26
  • 2015-09-14
相关资源
最近更新 更多