使用函数指针可实现自定义排序,需传入满足严格弱序的比较函数作为std::sort的第三参数。

在C++中使用std::sort时,如果需要对自定义类型排序或改变默认排序规则,可以通过自定义比较函数实现。关键在于传入一个满足严格弱序的可调用对象作为第三个参数。
最直接的方式是定义一个普通函数,然后将函数名作为参数传入
std::sort</)</p> <font color="#000000"> <ul> <li>函数必须返回<code>bool
const T&)true
例如按整数降序排列:
bool cmp(int a, int b) { return a > b; }std::vector<int> vec = {3, 1, 4, 1, 5};std::sort(vec.begin(), vec.end(), cmp);
定义一个重载了operator()的结构体或类,适合需要保存状态的场景。
立即学习“C++免费学习笔记(深入)”;
例如按绝对值排序:
struct CmpAbs {
bool operator()(int a, int b) const {
return abs(a) < abs(b);
}};std::sort(vec.begin(), vec.end(), CmpAbs{});
C++11起支持lambda,写法更简洁灵活,适合简单逻辑。
例如对二维点按横坐标升序、纵坐标降序排列:
std::vector<std::pair<int, int>> points = {{1,2}, {1,3}, {2,1}};std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) {
if (a.first != b.first) return a.first < b.first;
return a.second > b.second;});
比较函数必须满足“严格弱序”:不可自反(cmp(a,a)==false),且具有传递性。否则会导致未定义行为。
若使用类成员函数作为比较器,需声明为static,否则隐含的this指针会导致签名不匹配。
以上就是c++++中怎么自定义sort的比较函数_C++ std::sort自定义比较函数指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号