Let's say you are writing a code which include mapping of pairs (let's say coordinates in a grid) in C++.
Problem
If you try to do this directly:
std::unordered_map<std::pair<int, int>, std::string> gridMap;
Youβll get a compiler error. Why?
Because C++ (before C++20) doesnβt know how to hash a std::pair.
Solution: Custom Hash Function π
Let's create a pair hash
#include <iostream>
#include <unordered_map>
using namespace std;
struct pair_hash
{
template <class T1, class T2>
size_t operator()(const pair<T1, T2> &p) const
{
return hash<T1>{}(p.first) ^ (hash<T2>{}(p.second) << 1);
}
};
int main()
{
unordered_map<pair<int, int>, string, pair_hash> gridMap;
gridMap[{0, 0}] = "START";
gridMap[{1, 2}] = "Bomb π£";
gridMap[{2, 3}] = "Treasure π°";
gridMap[{5, 5}] = "END";
for (const auto &[pos, label] : gridMap)
{
cout << "(" << pos.first << ", " << pos.second << ") -> " << label << "\n";
}
}
Output
(5, 5) -> END
(2, 3) -> Treasure π°
(1, 2) -> Bomb π£
(0, 0) -> START
Top comments (0)