c++ - 使用点 (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
}
解决方案
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;
}
推荐阅读
- google-cloud-functions - 云函数的存储事件具有来自另一个事件的元数据
- javascript - 如何在 Reactjs 中使用数据目标和数据切换?
- mysql - 通过 MySQL 中的布尔值查找 JSON 对象路径
- python - 事务回滚
- node.js - 使用 Yarn 从另一个脚本调用一个脚本
- kotlin - 引用定义为成员的扩展函数;内联`with`
- laravel-6 - 重定向到嵌套控制器操作
- react-native - 使用 react-native-firebase-mlkit 视觉处理 OCR 图像后如何绘制边界框
- c - 在 PIC18F252 上与 ADC 的输出作斗争
- c++ - 为什么不允许将临时对象绑定到非常量引用?