std::vector和algorithm::sort,下面的代码出了什么问题

std::vector and algorithm::sort , What is wrong with following code

本文关键字:代码 什么 问题 vector algorithm sort std      更新时间:2023-10-16

我正在尝试使用algorithm::sortstd::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类的运算符。