c++怎么对自定义对象使用std::sort_c++自定义排序规则与比较函数示例

在C++中对自定义对象使用std::sort需提供排序规则,可通过重载

c++怎么对自定义对象使用std::sort_c++自定义排序规则与比较函数示例

在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 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

否则可能导致程序崩溃或未定义行为。

基本上就这些。根据需求选择合适的方式,lambda最常用也最清晰。

以上就是c++++怎么对自定义对象使用std::sort_c++自定义排序规则与比较函数示例的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482967.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 06:50:43
下一篇 2025年12月19日 06:50:54

相关推荐

发表回复

登录后才能评论
关注微信