[英]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.