How to Implement Custom Hash Functions for User-Defined Types in std::unordered_map?
Last Updated :
28 Apr, 2024
In C++ std::unordered_map
is a data structure that implements a hash table and allows fast access to each element based on its key. However, when we want to use user-defined types as keys, we need to provide a custom hash function. In this article, we will learn how to implement a custom hash function for user-defined types in std::unordered_map
.
Implement Custom Hash Functions for User-Defined Types in std::unordered_map
To implement a custom hash function, we need to define a functor (a struct or class that overloads the operator()
) that should take an object of our user-defined type as input and return the hash value. We need to pass that custom hash function as a template argument while declaring the std::unordered_map
using the below syntax.
Syntax to Use a Custom Hash Function in std::unordered_map
unordered_map<KeyType, ValueType, HashType>
Here,
KeyType
is a user-defined type, ValueType
is the type of the values in the map.HashType
is the custom hash function.
Approach:
- First, define a user-defined type(class, struct or any other user-defined type) for which you want to implement a custom hash function.
- Next, define a custom hash function that should be a struct or class that overloads the
operator() and i
t should take an object of your user-defined type as input and return a std::size_t
representing the hash value. - Finally, use the custom hash function as a template argument while declaring the
std::unordered_map
.
C++ Program to Implement Custom Hash Functions for User-Defined Types in std::unordered_map
The below program demonstrates how we can implement a custom hash function for user-defined types in std::unordered_map
in C++.
C++
// C++ program to Implement Custom Hash Functions for
// User-Defined Types in std::unordered_map
#include <iostream>
#include <unordered_map>
using namespace std;
struct Point {
int x, y;
// Constructor
Point(int x, int y)
: x(x)
, y(y)
{
}
bool operator==(const Point& other) const
{
return x == other.x && y == other.y;
}
};
// Define a custom hash function for the Point
struct PointHasher {
size_t operator()(const Point& p) const
{
// Combine hashes of x and y using the bitwise XOR
return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1);
}
};
int main()
{
// Create an unordered_map with the Point as key and int
// as value and pass hash function as template arguement
unordered_map<Point, int, PointHasher> point_map;
point_map[Point(1, 2)] = 10;
point_map[Point(3, 4)] = 20;
point_map[Point(5, 6)] = 30;
// printing the key-value pairs of point_map
for (const auto& pair : point_map) {
cout << "Point(" << pair.first.x << ", "
<< pair.first.y << "): " << pair.second
<< endl;
}
return 0;
}
OutputPoint(5, 6): 30
Point(3, 4): 20
Point(1, 2): 10
Time Complexity: O(1), for insertion, deletion, and access in std::unordered_map
Auxilliary Space: O(n), where n is the number of elements in the map.
Similar Reads
How to Create a Unordered Multimap of Tuples in C++? In C++, an unordered multimap container stores key-value pairs in no particular order. Unlike a map, an unordered multimap allows multiple values to be associated with a single key. In this article, we will learn how to create an unordered multimap of tuples in C++. For Example, Input: myPair1 = { "
2 min read
Different Ways to Initialize an unordered_map in C++ Initialization is the process of assigning the initial values to the std::unordered_map elements. In this article, we will learn different methods to initialize the std::unordered_map in C++.Table of ContentUsing Initializer ListBy Inserting Elements One by OneFrom Another std::unordered_mapFrom Ano
3 min read
How to Create a Unordered Multiset of Tuples in C++? In C++, an unordered multiset is a container that stores elements in no particular order, allowing fast retrieval of individual elements based on their value, much like unordered set containers, but allowing different elements to have equivalent values. In this article, we will learn how to create a
2 min read
std::try_emplace() in Maps and Unordered Maps of C++17 In this article, we are going to learn try_emplace method in Maps and Unordered Maps. This method was added in C++17 (i.e gcc 9.1) version. This new function proposed behaves similarly to emplace(), but has an advantage that is, it will not construct the object associated with the key, if the key al
2 min read
How to Create a Stack of Unordered_Multimap in C++? In C++, an unordered_multimap is an associative container that contains key-value pairs allowing multiple elements with the same key. In this article, we will learn how to create a stack of unordered_multimaps in C++. Example: Input: myMultimap1 = { {1, âC++â}, {2, âJavaâ}, {1, âPythonâ} }; myMultim
2 min read