答案:使用std::sort需提供满足严格弱序的比较函数,可采用普通函数、lambda表达式或函数对象形式,用于自定义排序规则。

在使用 C++ 的 std::sort 函数时,如果要对自定义类型或非默认顺序进行排序,需要提供比较函数。这个比较函数决定了元素之间的“小于”关系,从而控制排序结果。
基本语法与要求
std::sort 定义在 algorithm 头文件中,其常用形式为:
std::sort(begin, end, comp);
其中 comp 是可选的比较函数或函数对象。它必须满足“严格弱序”(Strict Weak Ordering),即对于任意两个元素 a 和 b:
如果 comp(a, b) 返回 true,则 a 应排在 b 前面。 不能同时有 comp(a, b) 和 comp(b, a) 为 true。 若 a 和 b 相等(互不小于对方),它们的相对顺序可能变化(不稳定排序除非特别保证)。
比较函数的三种写法
1. 普通函数
立即学习“C++免费学习笔记(深入)”;
适用于简单场景,比如按整数大小逆序排列:
bool cmp(int a, int b) {
return a > b; // 降序
}
std::vector vec = {3, 1, 4, 1, 5};
std::sort(vec.begin(), vec.end(), cmp);
也可以用于结构体:
struct Student {
std::string name;
int score;
};
bool cmpStudent(const Student& a, const Student& b) {
return a.score }
2. Lambda 表达式(推荐)
更灵活、可读性强,适合局部逻辑:
std::vector students = {/*…*/};
// 按分数降序,分数相同时按名字字典序升序
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 });
一行写法(简单情况):
std::sort(vec.begin(), vec.end(), [](int a, int b) { return a
3. 函数对象(仿函数)
适合复杂逻辑或需携带状态的情况:
struct CompareStudent {
bool operator()(const Student& a, const Student& b) const {
return a.score }
};
std::sort(students.begin(), students.end(), CompareStudent{});
常见注意事项
比较函数应返回 bool 类型,且不要修改传入参数(建议用 const 引用)。 避免写成 return a ,这会破坏严格弱序(相等时不应返回 true)。 Lambda 中若捕获变量,注意是否影响性能或逻辑。 结构体排序时,优先考虑复合条件下的分支处理。
基本上就这些。掌握这几种写法后,可以应对大多数排序需求。实际开发中推荐使用 lambda,简洁直观。
以上就是C++ sort函数自定义排序规则_C++ std::sort比较函数的写法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1487534.html
微信扫一扫
支付宝扫一扫