Sorting vector with point (x,y) values functionality, error: no matching function for call to object of type '__gnu_cxx::__ops::_Iter_less_iter'

Viewed 34

Im trying to sort a vector with points (x,y values), first by the x and then by the y value, this is my implementation, can someone tell me if this will work because Iam getting following error:

error: no matching function for call to object of type '__gnu_cxx::__ops::_Iter_less_iter'

Im guessing its from the std::sort in some way but im not 100% sure?

struct P {
float x, y;

P(float x_, float y_) : x(x_), y(y_) {}

};


std::vector<P> sortingPointsX(const std::vector<P> &p) {
     std::vector<P> copyP = p;
     std::sort(copyP.begin(), copyP.end(),
      [](P * a, P * b) -> bool
      { return a->x < b->x);
      


     
     std::sort(copyP.begin(), copyP.end(),
      [](P * a, P * b) -> bool
      { return a->y < b->y);

      return copyP
}
1 Answers

For starters instead of your own class struct P you could use the standard class template std::pair declared in the header <utility> because the operator < is already defined for this class template.

In this case you could just write

std::vector<std::pair<float, float>> sortingPointsX( const std::vector<std::pair<float, float>> &p ) 
{
    std::vector<std::pair<float, float>> copyP = p;

    std::sort( copyP.begin(), copyP.end() );

    return copyP;
}

As for your code then the type P * of the parameters of the lambda expressions is incorrect.

With your approach the first call of the function std::sort does not make a sense because the vector will be sorted anew in the second call of std::sort.

You could write

#include <tuple>
#include <vector>
#include <algorithm>

//...

std::vector<P> sortingPointsX(const std::vector<P> &p) {
     std::vector<P> copyP = p;

     std::sort( copyP.begin(), copyP.end(),
      []( const P &a, const P &b)
      { return std::tie( a.x, a.y ) < std::tie( b.x, b.y ); }
     );

     return copyP;
}
Related