开发者

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

I am trying sort std::vector using algorithm::sort , But I am getting runtime error Invalid operator <.

Following is my code.

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;
    }
};

Here is now I am calling it after populating the values.

std::sort( posVector.begin(), posVector.end(), compareX());


Your comparison function always returns true!


Your comparison functions always seem to return true. Returning false occasionally might be a good idea. And (to be serious) comparing (x.y) coordinates is not as trivial as it might seem to be - you probably want to think about it a bit before implementing it.


If you are using std::vector<Point> then must be

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;
    }
};

The problems of your code are

  • comparison classes accept pointers instead of objects being sorted (if std::vector<Point> is sorted, i.e. not std::vector<Point*>). If you are sorting vector of pointers then it is fine.

  • comparison classes contain mistyping - always return true (as already mentioned)

  • compareY use <= instead of <. It is bad idea because standard algorithms (including sorting) expect less-semantic (not less_or_equal-semantic).


Overload the '<' operator for the Point class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜