首页 > 解决方案 > 使用点 (x,y) 值功能对向量进行排序,错误:没有匹配函数调用类型为“__gnu_cxx::__ops::_Iter_less_iter”的对象

问题描述

我试图用点(x,y 值)对向量进行排序,首先是 x,然后是 y 值,这是我的实现,有人可以告诉我这是否可行,因为我收到以下错误:

错误:没有匹配函数调用类型为“__gnu_cxx::__ops::_Iter_less_iter”的对象

我以某种方式从 std::sort 猜测它,但我不是 100% 确定吗?

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
}

标签: c++sortingvectorstdstd-pair

解决方案


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

推荐阅读