example3_custom_hash.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <unordered_map>
#include <string>

struct Point {
    int x, y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

namespace std {
    template <>
    struct hash<Point> {
        size_t operator()(const Point& p) const {
            return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1);
        }
    };
}

int main() {
    std::unordered_map<Point, std::string> point_map;

    point_map[{1, 2}] = "Point A";
    point_map[{3, 4}] = "Point B";

    for (const auto& pair : point_map) {
        std::cout << "Point (" << pair.first.x << ", " << pair.first.y << "): " 
                  << pair.second << std::endl;
    }

    return 0;
}
Back to unordered_map