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

Viewed 219

I want to write my own Hash_function for an std::unordered_map instead of using the default one. I could find unordered_map::hash_function() on many websites. But using this i can only get the Hash value generated, using something like this :

/*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 ? So, that for example lets say for the key "Tom", i want hash value to be 100.

1 Answers

std::unordered_map is templated off of a Hasher that defaults to std::hash<Key>. You can change your variable to 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).

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. 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.

Related