c++处理结构的映射

c++ working with maps of structs

本文关键字:映射 结构 处理 c++      更新时间:2023-10-16

Point是以下形式的结构:

typedef struct Point {
    int x;
    int y;
    bool operator<(const Point &other) const
    {
        return ((this->x < other.x) && (this->y < other.y));
    };
    bool operator!=(const Point &other) const
    {
        return ((this->x != other.x) || (this->y != other.y));
    }
    bool operator==(const Point &other) const
    {
        return ((this->x == other.x) && (this->y == other.y));
    }
} Point;

我使用的是:

map<Point,int> points;

映射是用{{0,0},1}初始化的。该程序使用points.count(p)来检查点p是否是点图中的关键
出现问题,程序总是返回yes!即使是地图上没有的点。我的意思是,如果p不是积分的关键,我就得到了积分。count(p)==1(而不是0)
此外,当使用points.find(p)让迭代器检查接收到的点是否真的==0(事实并非如此)时,我得到了一个完全不同的点的引用
知道怎么解决这个问题吗?

您的operator<()定义不正确。假设我有a=Point{0,1}b=Point{1,1}。则a<bb<aa==b都不是真的,这使得算子不是可能点集上的排序。为了纠正这一点,你需要将其中一个维度(比如x)作为比较中的"主要"维度:

bool operator<(const Point &other) const
{
    return ((this->x < other.x) || 
             ((this->x == other.x) && (this->y < other.y));
};