std::vector和algorithm::sort,下面的代码出了什么问题
std::vector and algorithm::sort , What is wrong with following code
我正在尝试使用algorithm::sort
对std::vector
进行排序,但遇到运行时错误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;
}
};
你的代码有问题
比较类接受指针而不是被排序的对象(如果
std::vector<Point>
被排序,即不接受std::vector<Point*>
)。若你们正在对指针的矢量进行排序,那个么它是好的。比较类包含错误类型-总是返回true(如前所述)
compareY使用CCD_ 7而不是CCD_。这是个坏主意,因为标准算法(包括排序)期望更少的语义(而不是更少的_or_equal-semantic)。
重载'<'CCD_ 9类的运算符。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 需要以下代码的帮助,下面的代码有什么问题
- C++标准提案代码:什么是 N 和 P?
- C - 哈希算法代码什么都没有返回
- 将"12345678"转换为"1-234-5678",我的代码什么也没产生
- 在编译过程中,琐碎的(没有效果的)代码什么时候会被删除
- 有人能告诉我为什么这个代码什么都不打印吗