简体   繁体   中英

Sort vector of objects with multiple sorting criteria

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM