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

在C++中对自定义对象使用 std::sort,需要提供排序规则。可以通过重载操作符<、定义比较函数或使用lambda表达式来实现。
如果类中定义了<操作符,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 升序排列。
可以传入一个函数指针或函数对象作为比较规则。
示例:按姓名升序排序bool compareByName(const Student& a, const Student& b) {
return a.name < b.name;
}调用方式:
std::sort(students.begin(), students.end(), compareByName);
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;
});比较函数必须满足“严格弱序”规则:
否则可能导致程序崩溃或未定义行为。
基本上就这些。根据需求选择合适的方式,lambda最常用也最清晰。
以上就是c++++怎么对自定义对象使用std::sort_c++自定义排序规则与比较函数示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号