如何在cpp中为std::unordered_map<T>编写自定义hash_function?

我想为 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。

回答

std::unordered_map模板Hasher化为默认为std::hash<Key>. 您可以将变量更改为std::unordered_map<string, string, CustomHasher>. unordered_map然后将默认构造 a CustomHasher(如果您不能默认构造散列对象,它也可以在构造函数中传递)。

自定义散列器需要提供如下所示的调用运算符:

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

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

  • I didn't mean to ask to remove `noexcept`. Having a `noexcept` hasher is a good thing but the standard doesn't mandate non-throwing custom hashers. For example, libstdc++ does some internal optimization for `noexcept` hashers (it a hasher is not `noexcept` then a hash code has to be stored in a node, see https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/hashtable.h#L44). In that particular implementation `noexcept` alone is not enough to trigger optimization (hasher should also be "fast"), but in some other implementation it might be important.

以上是如何在cpp中为std::unordered_map&lt;T&gt;编写自定义hash_function?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>