![](/img/trans.png)
[英]Cannot specialize std::hash to store custom type in unordered_map
[英]How to write a custom hash_function for std::unordered_map<T> in cpp?
我想为 std::unordered_map 编写自己的 Hash_function,而不是使用默认的。 我可以在许多网站上找到 unordered_map::hash_function()。 但是使用这个我只能得到生成的 Hash 值,使用这样的东西:
/*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;
但是我怎样才能拥有更多的控制权并创建我自己的散列版本 function? 因此,例如让我们说键“Tom”,我希望 hash 值为 100。
std::unordered_map
是从默认为std::hash<Key>
的Hasher
模板化的。 您可以将变量更改为std::unordered_map<string, string, CustomHasher>
。 然后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
中的东西的 hash 值的代码通常是一个糟糕的设计。 想要自定义 hash function 有一些有效的用例,例如当您可以利用某些特定于您的数据的信息来生成更好的哈希时,但这些情况很少见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.