
在C++中使用std::sort函数时,如果需要按照自定义规则排序,可以通过传入比较函数、函数对象(仿函数)或Lambda表达式来实现。默认情况下,sort按升序排列基本类型,但对复杂数据类型(如结构体、类对象)或特殊排序需求,必须自定义比较逻辑。
1. 使用函数指针作为比较函数
最常见的方式是定义一个返回bool类型的函数,接受两个参数,当第一个参数应排在第二个之前时返回true。
```cpp bool cmp(int a, int b) { return a > b; // a 在 b 前面的条件 } std::vector
2. 结构体或类对象排序
对自定义类型排序时,比较函数需根据具体字段判断顺序。
```cpp struct Student { std::string name; int score; };// 按分数从高到低,分数相同时按名字字典序 bool cmpStudent(const Student& a, const Student& b) { if (a.score != b.score) { return a.score > b.score; } return a.name
std::vector
3. 使用Lambda表达式(推荐现代C++写法)
Lambda更简洁,适合简单逻辑,可直接在
sort调用中定义。立即学习“C++免费学习笔记(深入)”;
```cpp std::vectornums = {3, 1, 4, 1, 5}; std::sort(nums.begin(), nums.end(), [](int a, int b) { return a < b; // 升序 });
对结构体:
```cpp std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score == b.score) { return a.name b.score; }); ```4. 使用函数对象(仿函数)
适用于需要状态或复用的场景。
```cpp struct CmpByLength { bool operator()(const std::string& a, const std::string& b) { return a.length() std::vector<:string>words = {"hi", "hello", "c++"}; std::sort(words.begin(), words.end(), CmpByLength());注意事项:
- 比较函数必须满足严格弱序:即
cmp(a,a)必须为false,且若cmp(a,b)为true,则cmp(b,a)不能为true。 - 传递给
sort的比较逻辑应保证可预测、无副作用。 - 使用引用传参(尤其是结构体)避免拷贝开销。











