0

I want to override std::unordered_map::hash_function to my own hash function,which ways are possible to do it

imatcpie
  • 13
  • 3
  • 6
    Just pass the type of your own hash function as a third template argument of `std::unordered_map`. – Daniel Langr Aug 04 '21 at 07:45
  • 2
    Does this answer your question? [C++ unordered\_map using a custom class type as the key](https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key) – Const Aug 04 '21 at 08:50
  • 1
    What have you tried and what isn't working? Would this answer your question? https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key – mfnx Aug 04 '21 at 08:51
  • Start by examining the [documentation](https://en.cppreference.com/w/cpp/container/unordered_map), which describes the third template argument mentioned in the comment above. Then ask a question if you've written some code and are still having problems. – Useless Aug 06 '21 at 12:19

1 Answers1

1

As I understand you want to use the hash function to override the default hash function of the std::unordered_map. Or if there is no standard hash function available for the type of keys you want to use, then you have to implement your own hash function. So first you need to write your own hash function and append it in the namespace std example: The Hash for this class

`class IntWrapper`
{
public:
   IntWrapper(int i) : m_wrappedInt{i} {}
   int getValue() const { return m_wrappedInt; }
   bool operator==(const IntWrapper&) const = default;
private:
   int m_wrappedInt;
};

Will be

namespace std
{
template<> struct hash<IntWrapper>
{
size_t operator() (const IntWrapper& x) const {
    return std::hash<int>{} (x.getValue());
}
};
}

To write the actual hash function for IntWrapper, you write a specialization of the std::hash class template for IntWrapper. The std::hash class template is defined in . This specialization needs an implementation of the function call operator that calculates and returns the hash of a given IntWrapper instance.

There are five template parameters in unordered_map: the key type, the value type, the hash type, the equal comparison type, and the allocator type. With the last three parameters you can specify your own hash function, equal comparison function, and allocator function, respectively.