自定义Point类调用std::minmax_element报错,求对应比较函数实现方法
错误原因
std::minmax_element 算法默认使用 operator< 对容器元素进行大小比较,你自定义的Point类没有重载<运算符,编译器无法识别两个Point实例的大小比较规则,因此编译报错。另外你的示例代码遗漏了#include <vector>头文件,也是潜在的编译错误点。
解决方案
有两种常用实现方式,可根据使用场景选择:
方案1:重载Point类的<运算符
适合Point的大小比较规则固定、全局可复用的场景,重载后所有默认使用<比较的STL算法都可以直接适配Point类型:
#include <vector> #include <utility> #include <algorithm> using namespace std; class Point { public: int x, y, z; Point(int ix, int iy, int iz) : x(ix), y(iy), z(iz) {} // 比较规则:先比较x,x相等比较y,y相等比较z,可按需调整顺序 bool operator<(const Point& other) const { if (x != other.x) return x < other.x; if (y != other.y) return y < other.y; return z < other.z; } }; int main() { vector <Point> v = { {1, 1, 0}, {1, 2, 0}, {2, 2, 0}, {2, 1, 0} }; auto min_max = std::minmax_element(begin(v), end(v)); // 取值方式:min_max.first为最小元素迭代器,min_max.second为最大元素迭代器 return 0; }
方案2:传入自定义比较谓词
适合临时需要特殊比较规则、或不想修改Point类定义的场景,比较规则仅对当前std::minmax_element调用生效:
#include <vector> #include <utility> #include <algorithm> using namespace std; class Point { public: int x, y, z; Point(int ix, int iy, int iz) : x(ix), y(iy), z(iz) {} }; int main() { vector <Point> v = { {1, 1, 0}, {1, 2, 0}, {2, 2, 0}, {2, 1, 0} }; // 自定义比较Lambda,可按需调整比较逻辑 auto pointCompare = [](const Point& a, const Point& b) { if (a.x != b.x) return a.x < b.x; if (a.y != b.y) return a.y < b.y; return a.z < b.z; }; auto min_max = std::minmax_element(begin(v), end(v), pointCompare); return 0; }
两种方案的比较逻辑均可根据业务需求调整,比如要优先按z轴大小比较,仅需修改对应比较逻辑里的字段判断顺序即可。
内容的提问来源于stack exchange,提问作者getsuha
相关产品推荐
相关产品推荐

