问题描述
||
我正在尝试使用
algorithm::sort
对sort0ѭ进行排序,但出现运行时错误
Invalid operator <
。
以下是我的代码。
struct Point {
double x_cord;
double y_cord;
int id;
Point(int d,double x,double y) {
x_cord = x;
y_cord = y;
id = d;
}
};
struct compareX {
bool operator ()(Point * left,Point* right) const {
if (left->x_cord < right->x_cord)
return true;
return true;
}
};
struct compareY {
bool operator ()(Point * left,Point* right) const {
if (left->y_cord <= right->y_cord) return true;
return true;
}
};
现在,我在填充值后调用它。
std::sort( posvector.begin(),posvector.end(),compareX());
解决方法
您的比较函数始终返回true!
, 您的比较函数似乎总是返回true。偶尔返回false可能是一个好主意。而且(说真的)比较(x.y)坐标并不像看起来那么琐碎-您可能想在实现它之前先考虑一下。
, 如果您使用
std::vector<Point>
,则必须
struct compareX {
bool operator ()(const Point& left,const Point& right) const {
return left.x_cord < right.x_cord;
}
};
struct compareY {
bool operator ()(const Point& left,const Point& right) const {
return left->y_cord < right->y_cord;
}
};
您的代码的问题是
比较类接受指针而不是对对象进行排序(如果对“ 5”进行了排序,即对“ 8”进行了排序)。如果您要对指针向量进行排序,那很好。
比较类包含错误-始终返回true(如上所述)
compare use用<=
代替<
。这是个坏主意,因为标准算法(包括排序)期望语义较少(而不是less_or_equal-semantic)。
, 为Point
类重载\'<\'运算符。