2

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.

3

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Just a note: it doesn't have to be noexcept.
@Evg good point, removed it from the example.
I didn't mean to ask to remove noexcept. Having a noexcept hasher is a good thing but the standard doesn't mandate non-throwing custom hashers. For example, libstdc++ does some internal optimization for noexcept hashers (it a hasher is not noexcept then a hash code has to be stored in a node, see github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/…). In that particular implementation noexcept alone is not enough to trigger optimization (hasher should also be "fast"), but in some other implementation it might be important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.