std::sort需包含头文件,通过自定义cmp函数或lambda表达式实现特定排序规则,如降序或结构体字段排序,其中cmp(a,b)返回true表示a排在b前。
在C++中,std::sort 是一个非常高效的排序算法,定义在 gorithm> 头文件中。它默认对基本类型进行升序排序,但当我们处理自定义数据类型或需要特定排序规
则时,就需要提供自定义的比较函数(cmp)。
使用 sort 函数前,必须包含头文件:
#include标准调用格式为:
std::sort(起始迭代器, 结束迭代器, 比较函数);其中比较函数是可选参数。如果不传,默认按升序排列。
自定义排序的核心在于编写正确的比较函数。这个函数要返回一个布尔值,表示第一个参数是否“应该排在”第二个参数前面。
正确原则: 如果 cmp(a, b) 返回 true,则 a 会排在 b 前面。
(1)基础类型降序排序
bool cmp(int a, int b) { return a > b; // a 排在 b 前面当且仅当 a 更大 → 降序 }(2)结构体按字段排序
struct Student { int id; int score; }; bool cmp(const Student& a, const Student& b) { return a.score > b.score; // 按分数从高到低排 }调用方式:
vectorC++11 起支持 lambda,可以更简洁地写比较逻辑,尤其适合临时排序。
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { return a.score > b.score; });也可以一行内完成复杂判断,比如先按分数后排学号:
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score != b.score) return a.score > b.score; return a.id举例错误写法:
// 错误!相等时返回 true bool cmp(int a, int b) { return a >= b; }正确应为:
bool cmp(int a, int b) { return a > b; } 基本上就这些。掌握 cmp 的逻辑本质——决定“谁该在前”,就能灵活应对各种排序需求。