How do I customize hashing and equality with std::unordered_map?

To customize hashing and equality in std::unordered_map, you can define your own hash function and equality predicate. This is particularly useful when you need to store complex objects as keys in the map.

Below is an example where we create a custom struct and define a hash function and equality operator for it:

#include <iostream> #include <unordered_map> struct Point { int x, y; // Equality operator bool operator==(const Point& other) const { return x == other.x && y == other.y; } }; // Custom hash function struct PointHash { std::size_t operator()(const Point& point) const { return std::hash()(point.x) ^ std::hash()(point.y); } }; int main() { // Create an unordered_map with custom key type and hash function std::unordered_map pointMap; pointMap[{1, 2}] = "Point A"; pointMap[{3, 4}] = "Point B"; // Accessing value using custom key std::cout << pointMap[{1, 2}] << std::endl; // Output: Point A return 0; }

C++ std::unordered_map hashing equality custom hash function unordered_map example