对存储(x,y)点的vector排序报错:__gnu_cxx::__ops::_Iter_less_iter无匹配函数
错误原因排查
- 比较函数参数类型不匹配:你的
std::vector存储的是P类型的实例,而非P*指针,std::sort向比较函数传入的是迭代器解引用后的P对象引用,不是指针,所以lambda参数写P*会导致类型匹配失败,这就是你遇到的报错的直接原因。
- 比较函数参数类型不匹配:你的
- 排序逻辑错误:你分两次调用
std::sort分别排序x和y,第二次排序y的时候会完全覆盖第一次x排序的结果,无法实现「先按x排序,x相等再按y排序」的需求,需要把两个判断逻辑合并到同一个比较函数里。
- 排序逻辑错误:你分两次调用
- 语法错误:代码存在lambda闭包括号不匹配、
return语句缺少分号、lambda体缺少右大括号等语法问题。
- 语法错误:代码存在lambda闭包括号不匹配、
修正后代码
#include <vector> #include <algorithm> 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(), [](const P& a, const P& b) -> bool { // 先按x升序,x相等时按y升序 if (a.x != b.x) { return a.x < b.x; } return a.y < b.y; }); return copyP; }
内容的提问来源于stack exchange,提问作者Polynomial length of study
相关产品推荐
相关产品推荐

