DEV Community

Cover image for Hashing Pairs Like a Pro in C++
Anant Mishra
Anant Mishra

Posted on • Edited on

Hashing Pairs Like a Pro in C++

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;
Enter fullscreen mode Exit fullscreen mode

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";
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

(5, 5) -> END
(2, 3) -> Treasure 💰
(1, 2) -> Bomb 💣
(0, 0) -> START
Enter fullscreen mode Exit fullscreen mode

Top comments (0)