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

求解决STL的set的<运算符重载问题
本帖最后由 zr139898 于 2012-12-10 19:18:21 编辑 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;
}





------最佳解决方案--------------------
修改了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) 
------其他解决方案--------------------
#1的仁兄的方法,通过了,但是不知道原理
------其他解决方案--------------------
 ((x == c.x) && (y < c.y) ) );
    }
};

------其他解决方案--------------------
不用管我的原意(即先比较x,再比较y),不管坐标大小如何排,我只是想这个set能够正常插入坐标即可