在C++中对自定义对象使用std::sort需提供排序规则,可通过重载<操作符、自定义比较函数或lambda表达式实现;1. 重载<操作符可使std::sort直接调用;2. 自定义函数如compareByName可按姓名排序;3. lambda表达式最推荐,灵活支持复杂逻辑,如先按成绩降序再按姓名升序;4. 注意比较规则须满足严格弱序,否则可能导致未定义行为。

在C++中对自定义对象使用 std::sort,需要提供排序规则。可以通过重载操作符<、定义比较函数或使用lambda表达式来实现。
1. 通过重载操作符<进行排序
如果类中定义了<操作符,std::sort可以直接使用。
假设有一个表示学生的类:
struct Student {
std::string name;
int score;
// 重载 < 操作符,按成绩升序
bool operator<(const Student& other) const {
return score < other.score;
}
};
使用std::sort:
立即学习“C++免费学习笔记(深入)”;
std::vector<Student> students = {{"Alice", 85}, {"Bob", 72}, {"Charlie", 90}};
std::sort(students.begin(), students.end());
排序后,students 按 score 升序排列。
2. 使用自定义比较函数
可以传入一个函数指针或函数对象作为比较规则。
bool compareByName(const Student& a, const Student& b) {
return a.name < b.name;
}
调用方式:
std::sort(students.begin(), students.end(), compareByName);
3. 使用Lambda表达式(推荐)
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.name < b.name;
});
4. 注意事项
比较函数必须满足“严格弱序”规则:
- 不能有 a < a(反自反性)
- 如果 a < b 为真,则 b < a 必须为假(非对称性)
- 如果 a < b 且 b < c,则 a < c(传递性)
否则可能导致程序崩溃或未定义行为。
基本上就这些。根据需求选择合适的方式,lambda最常用也最清晰。











