How to create a map with key type point (x, y) and value type string in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_map>
#include <string>

// Define Point class
class Point {
private:
    int x;
    int y;

public:
    Point(int x_, int y_) : x(x_), y(y_) {}

    int getX() const { return x; }
    int getY() const { return y; }

    // Equality operator
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }

    // toString equivalent
    std::string toString() const {
        return "(" + std::to_string(x) + ", " + std::to_string(y) + ")";
    }
};

// Custom hash function for Point
struct PointHash {
    std::size_t operator()(const Point& p) const {
        return std::hash<int>()(p.getX()) ^ (std::hash<int>()(p.getY()) << 1);
    }
};

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

    map[Point(2, 7)] = "A";
    map[Point(3, 6)] = "B";
    map[Point(0, 0)] = "C";

    for (const auto& entry : map) {
        const Point& key = entry.first;
        const std::string& value = entry.second;
        std::cout << "x: " << key.getX() << ", y: " << key.getY() << " => " << value << std::endl;
    }
}




/*
run:
  
x: 0, y: 0 => C
x: 3, y: 6 => B
x: 2, y: 7 => A
  
*/

 



answered Aug 10, 2025 by avibootz
...