use*_*460 2 c++ sorting overloading vector object
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;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用对象排序sort.
但是,当我运行上面的代码时,我会遇到很多重复错误:
instantiated from here - sort (vect.begin(), vect.end());
我希望能够按x,y或dist进行排序.我想我可能需要重载>或==运算符,以便我使用sortC++标准库提供的?
重载代码怎么样?我知道如何重载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(); });
Run Code Online (Sandbox Code Playgroud)
注意,对于上面的示例,您要么定义成员函数getX,要么getY作为consts或const从lambdas的输入参数中删除限定符.
如果你的编译器不支持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();
}
Run Code Online (Sandbox Code Playgroud)
并打电话sort如下:
// sort by x
sort(vect.begin(), vect.end(), compare_x);
// sort by y
sort(vect.begin(), vect.end(), compare_y);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
813 次 |
| 最近记录: |