c++kquote>答案是使用比较函数、函数对象或Lambda表达式可实现std::sort自定义排序。1. 函数指针用于基本类型降序或自定义逻辑;2. 结构体排序需按字段写比较函数,如先按分数后按名字;3. Lambda表达式更简洁,推荐现代C++使用;4. 函数对象适合有状态或复用场景。

在C++中使用std::sort函数时,如果需要按照自定义规则排序,可以通过传入比较函数、函数对象(仿函数)或Lambda表达式来实现。默认情况下,sort按升序排列基本类型,但对复杂数据类型(如结构体、类对象)或特殊排序需求,必须自定义比较逻辑。
1. 使用函数指针作为比较函数
最常见的方式是定义一个返回bool类型的函数,接受两个参数,当第一个参数应排在第二个之前时返回true。
// 按整数降序排列
“`cppbool cmp(int a, int b) { return a > b; // a 在 b 前面的条件}std::vector nums = {3, 1, 4, 1, 5};std::sort(nums.begin(), nums.end(), cmp);“`
2. 结构体或类对象排序
对自定义类型排序时,比较函数需根据具体字段判断顺序。
“`cppstruct 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 students = {{“Alice”, 85}, {“Bob”, 90}, {“Charlie”, 85}};std::sort(students.begin(), students.end(), cmpStudent);
3. 使用Lambda表达式(推荐现代C++写法)
Lambda更简洁,适合简单逻辑,可直接在
sort调用中定义。立即学习“C++免费学习笔记(深入)”;
```cppstd::vector nums = {3, 1, 4, 1, 5};std::sort(nums.begin(), nums.end(), [](int a, int b) { return a < b; // 升序});
对结构体:
“`cppstd::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.score == b.score) { return a.name b.score;});“`
4. 使用函数对象(仿函数)
适用于需要状态或复用的场景。
“`cppstruct CmpByLength { bool operator()(const std::string& a, const std::string& b) { return a.length() std::vectorwords = {“hi”, “hello”, “c++”};std::sort(words.begin(), words.end(), CmpByLength());
注意事项:
- 比较函数必须满足严格弱序:即
cmp(a,a)必须为false,且若cmp(a,b)为true,则cmp(b,a)不能为true。 - 传递给
sort的比较逻辑应保证可预测、无副作用。 - 使用引用传参(尤其是结构体)避免拷贝开销。
以上就是c++++ sort函数怎么自定义比较函数_c++排序自定义规则实现的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482347.html
微信扫一扫
支付宝扫一扫