求解决STL的set的<运算符重载问题

zr139898 2012-12-10 07:16:23
VS2008专业版,把坐标结构体作为set的关键字,依次插入(0,0)、(0,1)、(1,0)、(1,1),出现xtree的Expression: invalid operator< 错误,我知道是<重载的问题,但是不懂得修改,求指导,谢谢!

---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Assertion Failed!

Program: ...ts of visual studio 2008\ACM\最小生成树\Debug\ZOJ 1203 Kruskal.exe
File: d:\microsoft visual studio 9.0\vc\include\xtree
Line: 638

Expression: invalid operator<

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)
---------------------------
中止(A) 重试(R) 忽略(I)
---------------------------



#include <set>
#include <iostream>
using namespace std;

struct Coordinate{ //浮点型坐标 结构体
float x, y;
Coordinate(float xx, float yy){
x = xx;
y = yy;
}
bool operator <(const Coordinate &c) const{
return ((x < c.x) || (!(x < c.x) && (y < c.y) ) );
}
};

int main(){
set<Coordinate> s;
s.insert(Coordinate(0, 0)); //插入(0,0)
s.insert(Coordinate(0, 1)); //插入(0,1)
s.insert(Coordinate(1, 0)); //插入(1,0),出错
s.insert(Coordinate(1, 1)); //插入(1,1),出错
return 0;
}




...全文
462 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
accept_cl 2015-09-02
  • 打赏
  • 举报
回复
在插入(1,0)时,首先和(0,0)比较,通过函数operator<比较得到false 再与(0,1)比较,operator<为true.那需要反过来比较,即用(0,1) 与(1,0)比较,使用operator< 还是真。那就认为这里的判断有问题,所以运行报错。 这里问什么两次operator< 都是真?
SF0606 2013-07-20
  • 打赏
  • 举报
回复
set的默认比较使用缺省的less仿函数,该仿函数使用<运算符比较用于决定set底层的红黑树排序,如果<的定义不是闭合为真(即a<b为假,b<a也为假)则无法决定该元素在红黑树中的位置。
hznat 2012-12-10
  • 打赏
  • 举报
回复
(0,0)(0,1)能正常插入 在插入(1,0)时,首先和(0,0)比较,通过函数operator<比较得到false 再与(0,1)比较,operator<为true.那需要反过来比较,即用(0,1) 与(1,0)比较,使用operator< 还是真。那就认为这里的判断有问题,所以运行报错。 也就是你的operator<应该能唯一确定排序。
zr139898 2012-12-10
  • 打赏
  • 举报
回复
#1的仁兄的方法,通过了,但是不知道原理
zr139898 2012-12-10
  • 打赏
  • 举报
回复
不用管我的原意(即先比较x,再比较y),不管坐标大小如何排,我只是想这个set能够正常插入坐标即可
hznat 2012-12-10
  • 打赏
  • 举报
回复
修改了operator函数。不知道这样修改是否满足你本意: 先比较x,如果小于,则Coordinate小于。 如果相等,再比较y.
struct Coordinate{  //浮点型坐标 结构体
    float x, y;
    Coordinate(float xx, float yy){
        x = xx;
        y = yy;
    }
    bool operator <(const Coordinate &c) const{
        return ((x < c.x) || ((x == c.x) && (y < c.y) ) );
    }
};

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧