c ++使用结构图[重复]
Posted
技术标签:
【中文标题】c ++使用结构图[重复]【英文标题】:c++ working with maps of structs [duplicate] 【发布时间】:2016-05-06 07:57:05 【问题描述】: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 是否是点映射中的键。 有问题,程序总是返回是!即使对于不在地图上的点。我的意思是如果 p 不是积分的关键,我得到 points.count(p)==1 (而不是 0)。 此外,当使用 points.find(p) 让迭代器检查接收到的点是否真的 ==0(不是)时,我得到了对完全不同点的引用.. 知道如何解决这个问题吗?
【问题讨论】:
您的operator<
没有定义Strict Weak Ordering。
你是对的,当我用 Point=0,0 和 int = 1 初始化点时;我收到 1,1 不是键,而 0,1 是.. 我该如何解决?编辑:@BoBTFish 嘿,我错过了你的链接,现在我正在检查它
This question has answers for 3 points.
@BoBTFish 我刚刚根据第一个链接进行了更新,它有效!非常感谢鲍勃
另外,typedef struct Point ... Point;
结构仅与 C 相关,与 C++ 无关。
【参考方案1】:
您的operator<()
定义不正确。假设我有a=Point0,1
和b=Point1,1
。那么a<b
、b<a
和a==b
都不为真,这使得运算符不是可能点集的排序。为了纠正这个问题,您需要将其中一个维度(比如 x)设为比较中的“主要”维度:
bool operator<(const Point &other) const
return ((this->x < other.x) ||
((this->x == other.x) && (this->y < other.y));
;
【讨论】:
以上是关于c ++使用结构图[重复]的主要内容,如果未能解决你的问题,请参考以下文章