如何在 cpp 中为 std::unordered_map<T> 编写自定义 hash_function?
How to write a custom hash_function for std::unordered_map<T> in cpp?
我想为 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
是从默认为 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
中的某些内容的哈希值的代码通常是一个糟糕的设计。有一些需要自定义哈希函数的有效用例,例如当您可以利用一些特定于您的数据的信息来生成更好的哈希值时,但这些情况非常罕见。
我想为 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
是从默认为 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
中的某些内容的哈希值的代码通常是一个糟糕的设计。有一些需要自定义哈希函数的有效用例,例如当您可以利用一些特定于您的数据的信息来生成更好的哈希值时,但这些情况非常罕见。