C++怎么自定义sort函数的比较规则_C++ sort自定义比较函数写法示例

在C++中自定义sort排序规则可通过函数指针、lambda表达式或重载operator()实现,需满足严格弱序要求。

c++怎么自定义sort函数的比较规则_c++ sort自定义比较函数写法示例

在C++中使用sort函数自定义比较规则,可以让排序按照我们指定的逻辑进行。默认情况下,sort按升序排列元素,但通过传入自定义的比较函数或函数对象,可以灵活控制排序方式。

1. 使用函数指针定义比较规则

可以写一个返回bool类型的函数,接收两个参数,当第一个参数应排在第二个之前时返回true

示例:按整数降序排列

#include 
#include
#include

bool cmp(int a, int b) {
return a > b; // 降序
}

int main() {
std::vector vec = {3, 1, 4, 1, 5};
std::sort(vec.begin(), vec.end(), cmp);
for (int x : vec) std::cout << x << " "; // 输出: 5 4 3 1 1
return 0;
}

2. 使用lambda表达式(推荐)

C++11起支持lambda,写法更简洁,适合简单逻辑。

立即学习“C++免费学习笔记(深入)”;

示例:按字符串长度排序

#include 
#include
#include
#include

int main() {
std::vector words = {"hi", "hello", "cpp", "sort"};
std::sort(words.begin(), words.end(),
[](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
for (const auto& w : words)
std::cout << w << " "; // 输出: hi cpp sort hello
return 0;
}

3. 使用结构体重载operator()

适用于复杂逻辑或多处复用的情况。

示例:按二维点到原点距离排序

#include 
#include
#include

struct Point {
int x, y;
};

struct CmpByDistance {
bool operator()(const Point& a, const Point& b) {
return (a.x*a.x + a.y*a.y) < (b.x*b.x + b.y*b.y);
}
};

int main() {
std::vector points = {{3,4}, {1,1}, {0,2}};
std::sort(points.begin(), points.end(), CmpByDistance());
// 排序后顺序: (1,1), (0,2), (3,4)
return 0;
}

注意事项

自定义比较函数必须满足“严格弱序”关系:

不能对相同元素返回true(即cmp(a,a)必须为false) 如果cmp(a,b)true,则cmp(b,a)应为false 避免使用>=,只用>

基本上就这些。根据场景选择函数、lambda或仿函数,注意逻辑正确性即可。

以上就是C++怎么自定义sort函数的比较规则_C++ sort自定义比较函数写法示例的详细内容,更多请关注创想鸟其它相关文章!

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

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 05:05:27
下一篇 2025年12月19日 05:05:42

相关推荐

发表回复

登录后才能评论
关注微信