C++中自定义排序通过std::sort配合比较函数、Lambda或重载

在C++中,自定义排序规则主要通过std::sort配合比较函数或比较器实现。默认情况下,std::sort对基本类型按升序排列,但面对复杂数据类型或特殊排序需求时,就需要手动定义排序规则。
使用函数指针定义比较规则
最直接的方式是编写一个返回布尔值的比较函数,用于指定两个元素之间的“小于”关系。
例如,对整数数组进行降序排序:
#include #include #include bool descending(int a, int b) { return a > b; // 当a大于b时,a应排在b前面}int main() { std::vector nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end(), descending); for (int n : nums) std::cout << n << " "; // 输出:9 8 5 2 1}
使用Lambda表达式简化比较逻辑
C++11起支持Lambda,适合简单、局部使用的排序规则。
立即学习“C++免费学习笔记(深入)”;
比如按绝对值大小排序:
std::vector nums = {-3, 1, -7, 4, 0};std::sort(nums.begin(), nums.end(), [](int a, int b) { return abs(a) < abs(b); // 按绝对值升序});// 结果:0 1 -3 4 -7
对结构体或类自定义排序
当排序对象是自定义类型时,可通过函数对象(仿函数)或Lambda明确排序依据。
定义一个表示学生的信息结构体,按成绩降序、姓名升序排列:
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.name b.score; // 否则按成绩降序});
此方法灵活控制多字段排序优先级。
重载操作符实现默认排序
若某类型经常需要排序,可在结构体内重载运算符,使std::sort无需额外参数。
struct Point { int x, y; bool operator<(const Point& other) const { return x < other.x || (x == other.x && y < other.y); }};std::vector pts = {{2,3}, {1,5}, {2,1}};std::sort(pts.begin(), pts.end()); // 使用默认比较// 排序后:(1,5), (2,1), (2,3)
基本上就这些常见方式。函数指针适合复用逻辑,Lambda适合临时规则,重载适合类型内置顺序明确的情况。掌握这些方法,就能应对大多数排序场景。
以上就是C++如何自定义排序函数的规则_C++排序算法与比较器自定义示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482789.html
微信扫一扫
支付宝扫一扫