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

在C++中使用std::sort时,如果需要对自定义类型排序或改变默认排序规则,可以通过自定义比较函数实现。关键在于传入一个满足严格弱序的可调用对象作为第三个参数。
函数指针方式
最直接的方式是定义一个普通函数,然后将函数名作为参数传入
std::sort)类型
- 函数必须返回
bool
const T&)true
例如按整数降序排列:
bool cmp(int a, int b) { return a > b; }std::vectorstd::sort(vec.begin(), vec.end(), cmp);
仿函数(函数对象)
定义一个重载了operator()的结构体或类,适合需要保存状态的场景。
立即学习“C++免费学习笔记(深入)”;
例如按绝对值排序:
struct CmpAbs {
bool operator()(int a, int b) const {
return abs(a)
}};std::sort(vec.begin(), vec.end(), CmpAbs{});
Lambda表达式(推荐)
C++11起支持lambda,写法更简洁灵活,适合简单逻辑。
例如对二维点按横坐标升序、纵坐标降序排列:
std::vector<:pair 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
return a.second > b.second;});
比较函数必须满足“严格弱序”:不可自反(cmp(a,a)==false),且具有传递性。否则会导致未定义行为。
若使用类成员函数作为比较器,需声明为static,否则隐含的this指针会导致签名不匹配。











