在 c++ 中,std::sort可通过自定义比较函数实现降序、结构体 字段排序等复杂逻辑,支持函数 指针 、Lambda 表达式和函数 对象 ;例如用bool cmp(int a, int b) {return a > b;} 可实现降序排序,Lambda 可用于按 字符串 长度排序,结构体则可通过 成员变量 如分数进行排序,需注意保持严格弱序并避免修改外部状态。

在 C ++ 中使用 std::sort 时,可以通过自定义比较函数来控制排序规则。默认情况下,sort按升序 排列 元素,但通过传入自定义的比较函数或函数对象,可以实现降序、结构体排序、字符串长度排序等复杂逻辑。
基本语法:自定义比较函数
自定义比较函数是一个返回 bool 类型的函数,接受两个参数,当第一个参数应排在第二个之前时返回true。
示例:整数降序排序
#include <algorithm> #include <vector> #include <iostream> bool cmp(int a, int b) {return a > b; // 降序} int main() { std::vector<int> nums = {3, 1, 4, 1, 5}; std::sort(nums.begin(), nums.end(), cmp); for (int x : nums) std::cout << x << " "; // 输出:5 4 3 1 1 }
使用 Lambda 表达式
Lambda 让定义比较规则更简洁,适合简单逻辑。
示例:按字符串长度排序
std::vector<std::string> words = {"hi", "hello", "yes", "ok"}; std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {return a.length() < b.length();}); // 结果:hi ok yes hello(按长度升序)
对结构体或类进行排序
常用于根据对象的某个字段排序。
立即学习“C++ 免费学习笔记(深入)”;
示例:按学生分数排序
struct Student {std::string name; int score;}; std::vector<Student> students = {{"Alice", 85}, {"Bob", 92}, {"Charlie", 78} }; std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {return a.score > b.score; // 分数从高到低}); // 排序后:Bob(92), Alice(85), Charlie(78)
注意事项和技巧
写比较函数时需注意以下几点:
- 比较函数必须是 严格弱序,即不能出现 a <b 和 b <a 同时为真
- 不要在比较中修改外部状态,避免未定义行为
- 若频繁调用,建议使用函数对象(重载
operator())提升性能 - 可结合
std::greater<>、std::less<>等预定义函数对象简化代码
基本上就这些。掌握自定义比较函数后,就能灵活应对各种排序需求了。


