c++中自定义排序通过std::sort配合比较函数、Lambda或重载<操作符实现。1. 函数指针用于复用逻辑,如降序排序;2. Lambda表达式简化临时规则,如按绝对值排序;3. 结构体排序可用Lambda指定多字段优先级,如成绩降序、姓名升序;4. 重载<操作符为类定义默认顺序,如Point按x、y坐标排序。这些方法覆盖基本类型、复杂对象及多条件排序需求,灵活应对各类场景。

在C++中,自定义排序规则主要通过std::sort配合比较函数或比较器实现。默认情况下,std::sort对基本类型按升序排列,但面对复杂数据类型或特殊排序需求时,就需要手动定义排序规则。
使用函数指针定义比较规则
最直接的方式是编写一个返回布尔值的比较函数,用于指定两个元素之间的“小于”关系。
例如,对整数数组进行降序排序:
#include <algorithm> #include <vector> #include <iostream> bool descending(int a, int b) { return a > b; // 当a大于b时,a应排在b前面 } int main() { std::vector<int> nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end(), descending); for (int n : nums) std::cout << n << " "; // 输出:9 8 5 2 1 }
使用Lambda表达式简化比较逻辑
C++11起支持Lambda,适合简单、局部使用的排序规则。
立即学习“C++免费学习笔记(深入)”;
比如按绝对值大小排序:
std::vector<int> nums = {-3, 1, -7, 4, 0}; std::sort(nums.begin(), nums.end(), [](int a, int b) { return abs(a) < abs(b); // 按绝对值升序 }); // 结果:0 1 -3 4 -7
对结构体或类自定义排序
当排序对象是自定义类型时,可通过函数对象(仿函数)或Lambda明确排序依据。
定义一个表示学生的信息结构体,按成绩降序、姓名升序排列:
struct Student { std::string name; int score; }; std::vector<Student> students = { {"Alice", 85}, {"Bob", 90}, {"Charlie", 85} }; std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score == b.score) return a.name < b.name; // 成绩相同时按姓名升序 return a.score > b.score; // 否则按成绩降序 });
此方法灵活控制多字段排序优先级。
重载操作符实现默认排序
若某类型经常需要排序,可在结构体内重载<运算符,使std::sort无需额外参数。
struct Point { int x, y; bool operator<(const Point& other) const { return x < other.x || (x == other.x && y < other.y); } }; std::vector<Point> pts = {{2,3}, {1,5}, {2,1}}; std::sort(pts.begin(), pts.end()); // 使用默认比较 // 排序后:(1,5), (2,1), (2,3)
基本上就这些常见方式。函数指针适合复用逻辑,Lambda适合临时规则,重载<适合类型内置顺序明确的情况。掌握这些方法,就能应对大多数排序场景。