std::sort传入lambda表达式是最直接的自定义排序方式,需注意参数类型为const T&、捕获语法正确及避免拷贝开销;函数指针或仿函数类仅在需复用或带状态时选用。

std::sort 传入 lambda 表达式是最直接的方式
默认情况下 std::sort 对数组(或迭代器范围)做升序排列,但只要提供一个二元谓词(接受两个 const T& 参数、返回 bool),就能自定义顺序。lambda 是最常用也最轻量的选择。
常见错误是把 lambda 写成捕获外部变量却没声明 [&] 或 [=],或者参数类型写错(比如漏掉 const & 导致拷贝开销或编译失败)。
- 对
int数组按绝对值排序:int arr[] = {-5, 3, -1, 8};<br>std::sort(arr, arr + 4, [](int a, int b) { return std::abs(a) < std::abs(b); }); - 对结构体数组按某个成员排序,必须确保 lambda 参数类型与数组元素类型一致:
struct Person { std::string name; int age; };<br>Person people[] = {{"Alice", 30}, {"Bob", 25}};<br>std::sort(people, people + 2, [](const Person& a, const Person& b) { return a.age < b.age; }); - 如果要降序,直接把比较符反过来:
a > b,别用std::greater()—— 它只适用于默认可比较类型,不兼容自定义逻辑
使用函数指针或仿函数类也能工作,但更啰嗦
lambda 覆盖了 95% 的场景;只有当排序逻辑需复用、或需带状态(比如按某运行时变量动态调整规则)时,才考虑函数指针或仿函数类。
容易踩的坑是函数指针签名不匹配:必须是 bool(*)(const T&, const T&),不能有额外参数,也不能返回非 bool 类型。
立即学习“C++免费学习笔记(深入)”;
- 函数指针示例(注意
static或全局作用域):bool cmp_by_len(const std::string& a, const std::string& b) {<br> return a.length() < b.length();<br>}<br>// 使用:<br>std::sort(strs, strs + n, cmp_by_len); - 仿函数类适合带状态,比如按指定字段索引排序二维数组:
struct ColumnCmp {<br> int col;<br> ColumnCmp(int c) : col(c) {}<br> bool operator()(const std::vector<int>& a, const std::vector<int>& b) const {<br> return a[col] < b[col];<br> }<br>};<br>std::sort(matrix, matrix + rows, ColumnCmp(2));
原生数组和 std::array 都支持,但 std::vector 更安全
std::sort 接收的是迭代器(指针),所以原生数组用 arr 和 arr + n,std::array 用 arr.begin()/arr.end(),std::vector 同理。三者语法一致,但 vector 自带 size()、内存自动管理,不容易越界或算错长度。
典型错误是把原生数组名直接传给 std::sort(arr, n, cmp) —— 第二个参数必须是指针,不是长度;或对 std::array 忘记调用 .begin(),导致编译失败。
- 正确写法对比:
int raw[5] = {1,2,3,4,5};<br>std::sort(raw, raw + 5, cmp); // ✅<br><br>std::array<int,5> arr = {1,2,3,4,5};<br>std::sort(arr.begin(), arr.end(), cmp); // ✅<br><br>std::vector<int> vec = {1,2,3,4,5};<br>std::sort(vec.begin(), vec.end(), cmp); // ✅ - 不要写
std::sort(arr, 5, cmp)—— 编译不过;也不要对 raw 数组用std::size(arr)(C++17 才支持,且需包含<iterator>)
稳定性:std::stable_sort 才保序,std::sort 不保证
如果相等元素的原始相对位置需要保留(比如先按姓氏排、再按名字排的二次排序),必须用 std::stable_sort。而 std::sort 是非稳定排序,标准不保证等值元素顺序,实际实现(如 introsort)通常会打乱它们。
性能上,std::stable_sort 一般比 std::sort 慢一点、内存多一点,但多数场景差异不明显。别为了“可能稳定”而盲目换用 —— 只在真有等值元素顺序要求时才切。
- 例如对学生成绩数组按班级分组后,在各班内按分数排,又想保持原始录入顺序:
std::stable_sort(students, students + n, [](const Student& a, const Student& b) {<br> return a.score > b.score; // 降序,且同分者保持原序<br>}); - 若用
std::sort替代,同分学生的顺序就不可预测了


















