简体   繁体   English

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

[英]How to write a custom hash_function for std::unordered_map<T> in cpp?

I want to write my own Hash_function for an std::unordered_map instead of using the default one.我想为 std::unordered_map 编写自己的 Hash_function,而不是使用默认的。 I could find unordered_map::hash_function() on many websites.我可以在许多网站上找到 unordered_map::hash_function()。 But using this i can only get the Hash value generated, using something like this:但是使用这个我只能得到生成的 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;

But how can i have more control and create my own version of the hashing function?但是我怎样才能拥有更多的控制权并创建我自己的散列版本 function? So, that for example lets say for the key "Tom", i want hash value to be 100.因此,例如让我们说键“Tom”,我希望 hash 值为 100。

std::unordered_map is templated off of a Hasher that defaults to std::hash<Key> . std::unordered_map是从默认为std::hash<Key>Hasher模板化的。 You can change your variable to std::unordered_map<string, string, CustomHasher> .您可以将变量更改为std::unordered_map<string, string, CustomHasher> unordered_map will then default construct a CustomHasher (it can also be passed in the constructor if you can't default construct your hashing object).然后unordered_map将默认构造一个CustomHasher (如果您不能默认构造散列对象,它也可以在构造函数中传递)。

A custom hasher needs to provide a call operator such as the following:自定义哈希器需要提供如下调用运算符:

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

Note: Writing code that depends on the hash values of something stored in an unordered_map is typically a bad design.注意:编写依赖于存储在unordered_map中的东西的 hash 值的代码通常是一个糟糕的设计。 There are valid use cases for wanting a custom hash function such as when you can exploit some information specific to your data to generate better hashes, but those cases are quite rare.想要自定义 hash function 有一些有效的用例,例如当您可以利用某些特定于您的数据的信息来生成更好的哈希时,但这些情况很少见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM