class Point2D
{
friend ostream& operator<< (ostream&, const Point2D&);
protected:
int x; //can sort by x
int y; //can sort by y
double dist; //can sort by dist
public:
Point2D () {x=0; y=0;}
Point2D (int a, int b) {x=a; y=b;}
void setX (int);
void setY (int);
void setDist();
double getDist() const;
int getX ();
int getY ();
}
int main()
{
vector<Point2D> vect;
sort (vect.begin(), vect.end());
//Print all vector elements
for (int x=0; x<vect.size(); x++)
cout << vect[x] << endl;
}
我正在尝试排序向量的对象使用sort
.
但是当我运行上面的代码时,我得到了大量重复的错误:
instantiated from here - sort (vect.begin(), vect.end());
我希望能够通过x, y或dist进行排序。我想我可能需要重载>
或==
操作符,以便我使用c++ std库提供的sort
?
重载的代码是什么样的?我知道如何重载ostream操作符,如<<
来显示数据,但在这种复杂的情况下,我们如何做重载,以允许我们使用sort
?
如果你的编译器支持c++ 11,你可以这样做:
vector<Point2D> vect;
// sort by x
sort (vect.begin(), vect.end(), [](Point2D const &a, Point2D const &b) { return a.getX() < b.getX(); });
// sort by y
sort (vect.begin(), vect.end(), [](Point2D const &a, Point2D const &b) { return a.getY() < b.getY(); });
注意,要使上面的示例正常工作,您必须将成员函数getX
和getY
定义为const
,或者从lambdas的输入参数中删除const
限定符。
如果你的编译器不支持c++ 11,那么你可以定义如下的比较:
bool compare_x(Point2D const &a, Point2D const &b)
{
return a.getX() < b.getX();
}
bool compare_y(Point2D const &a, Point2D const &b)
{
return a.getY() < b.getY();
}
并像下面这样调用sort
:
// sort by x
sort(vect.begin(), vect.end(), compare_x);
// sort by y
sort(vect.begin(), vect.end(), compare_y);