-1

I would like help figuring out how to use the next_permutation function on a vector of objects. I've read about people using the comp parameter, but I don't understand it. I thought the overloaded operators would fix things, but I'm still getting thrown errors. Please help me with my syntax and/or explain (with examples) the comp parameter of the next_permutation function! Thanks!

In my main file:

vector<Point> source;

//fill vector with Points, say 4 of them (1,2)(2,3)(3,4)(4,5)

next_permutation(source.begin(), source.end()); // at run I get error "Invalid operands to binary expression ('Const Point' and 'Const Point)"

My simple Point class:

class Point {
private:
    double xval, yval;
public:
    Point(int x = 0, int y = 0) {
        xval = x;
        yval = y;
    }

    int x() { return xval; }
    int y() { return yval; }

    friend bool operator<(Point& lhs, Point& rhs){
        return lhs.x() < rhs.x() || (lhs.x()==rhs.x() && lhs.y()<rhs.y()) ;
    }

    friend bool operator==(Point& lhs, Point& rhs) {
        return lhs.x()==rhs.x() && lhs.y()==rhs.y();
    }

};

EDIT: This also throws the same error:

int x() const { return xval; }
int y() const { return yval; }

friend bool operator<(const Point& lhs, const Point& rhs){
    return lhs.x() < rhs.x() || (lhs.x()==rhs.x() && lhs.y()<rhs.y()) ;
}

friend bool operator==(const Point& lhs, const Point& rhs) {
    return lhs.x()==rhs.x() && lhs.y()==rhs.y();
}

This also throws the same error:

int x() const { return xval; }
int y() const { return yval; }

bool operator<(const Point& lhs){
    return lhs.x() < x() || (lhs.x()==x() && lhs.y()<y()) ;
}

bool operator==(const Point& lhs) {
    return lhs.x()==x() && lhs.y()==y();
}
4

2 回答 2

1

使用 const 引用和 const getter 函数。

int x() const { return xval; }
int y() const { return yval; }

friend bool operator<(const Point& lhs, const Point& rhs){
    return lhs.x() < rhs.x() || (lhs.x()==rhs.x() && lhs.y()<rhs.y()) ;
}

friend bool operator==(const Point& lhs, const Point& rhs) {
    return lhs.x()==rhs.x() && lhs.y()==rhs.y();
}

http://liveworkspace.org/code/4Drerr $0

于 2013-01-30T05:50:38.077 回答
0

Getter 函数应该是 const 成员函数,还有什么理由从 double 转换为 int?

尝试:

double x() const { return xval; }
double y() const { return yval; }
于 2013-01-30T05:53:25.297 回答