Search code examples
c++stlhashmapoperator-overloadingunordered-map

operator overloading() for a user-defined type in unordered_map


I was looking at this post C++ unordered_map using a custom class type as the key

  1. I understand that we need to redefine equality and hash code for a custom type key.
  2. I know how the operator overloading works in general.

However, what does operator() have to do with the hash code?
Does unordered_map internally evaluate a key with () operator somewhere?


Solution

  • The std::unordered_map uses an std::hash object to calculate the hash-values.

    It will use the hash-object like a function, calling the operator() to do the calculation.

    As a simple example, for an int key, it will be something like this:

    int key = 123;  // Or whatever value...
    
    std::hash<int> hash_object;
    auto hash_value = hash_object(key);  // Calls hash_object.operator()(key)