答案:C++中可通过自定义比较函数、lambda表达式、函数对象等方式控制sort排序规则,如降序排序、按结构体成员排序等,需满足严格弱序要求。

在C++中使用sort函数进行排序时,如果需要对自定义数据类型排序或改变默认的排序规则,可以通过自定义比较函数来实现。标准库中的std::sort允许传入一个比较函数或函数对象作为第三个参数,从而控制元素之间的排序方式。
1. 使用函数指针定义比较函数
最简单的方式是定义一个返回bool类型的函数,接收两个参数,当第一个参数应排在第二个之前时返回true。
例如,对整数数组进行降序排序:
#include#include #include bool cmp(int a, int b) { return a > b; // 降序 }
int main() { std::vector
vec = {3, 1, 4, 1, 5}; std::sort(vec.begin(), vec.end(), cmp); for (int x : vec) std::cout zuojiankuohaophpcnzuojiankuohaophpcn x zuojiankuohaophpcnzuojiankuohaophpcn " "; // 输出:5 4 3 1 1 return 0;}
立即学习“C++免费学习笔记(深入)”;
2. 使用lambda表达式(推荐)
C++11起支持lambda,写起来更简洁,尤其适合在局部使用。
同样实现降序排序:
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b;
});
lambda可以捕获外部变量,灵活性更高。比如按与某个值的接近程度排序:
int target = 5;
std::sort(vec.begin(), vec.end(), [target](int a, int b) {
return abs(a - target) < abs(b - target);
});
3. 对结构体或类自定义排序
当排序对象是结构体时,需明确比较逻辑。例如按学生的成绩排序,成绩相同时按名字字母序:
struct Student {
std::string name;
int score;
};
std::vector 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.score > b.score; // 成绩高者优先
return a.name < b.name; // 成绩相同按名字升序
});
4. 使用函数对象(仿函数)
定义一个重载了()操作符的类,适用于复杂或复用场景:
struct Greater {
bool operator()(int a, int b) {
return a > b;
}
};
std::sort(vec.begin(), vec.end(), Greater());
注意:比较函数必须满足严格弱序(strict weak ordering),即:
- 不能对相同元素返回true(如
cmp(a,a)必须为false) - 若
cmp(a,b)为true,则cmp(b,a)应为false - 具有传递性
基本上就这些。使用lambda最方便,结构体排序也很常见,关键是写好比较逻辑。只要返回bool并符合排序要求,sort就能正确工作。









