Reputation: 17454
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;
}
I am trying to sort vector of objects using sort
.
But when I run my codes above, I get plenty of repeating errors saying:
instantiated from here - sort (vect.begin(), vect.end());
I want to be able to sort by either x, y or dist.
I guess I probably need to overload the >
or ==
operators in order for me to use the sort
provided by C++ std library?
How would the code for overloading look like? I know how to overload ostream operators like <<
to display data, but in this complicated situation, how do we do the overloading in order to allow us to use sort
?
Upvotes: 2
Views: 1183
Reputation: 42909
If your compiler supports C++11, You could do something like:
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(); });
Note, for the above example to work you have either to define your member functions getX
and getY
as const
s or remove the const
qualifiers from the input arguments of the lambdas.
If your compiler doesn't support C++11 then you can define comparables like below:
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();
}
and call sort
like below:
// sort by x
sort(vect.begin(), vect.end(), compare_x);
// sort by y
sort(vect.begin(), vect.end(), compare_y);
Upvotes: 5