c++中如何自定义排序规则排序vector_c++ vector自定义排序技巧

答案:C++中可通过std::sort结合函数指针、Lambda表达式或函数对象对vector进行自定义排序,如按成绩降序或名字升序,推荐使用Lambda实现简洁逻辑。

c++中如何自定义排序规则排序vector_c++ vector自定义排序技巧

在C++中,对vector进行自定义排序是常见需求,尤其是在处理复杂数据类型时。我们可以通过std::sort配合自定义比较函数、函数对象或Lambda表达式来实现灵活排序。下面介绍几种常用方法。

使用函数指针作为比较规则

如果要排序的数据是简单结构体或类,可以定义一个全局比较函数,然后传给std::sort

示例:

假设有一个学生结构体,按成绩降序排列

#include #include #include struct Student {    std::string name;    int score;};bool compareByScore(const Student& a, const Student& b) {    return a.score > b.score; // 降序}int main() {    std::vector students = {{"Alice", 85}, {"Bob", 92}, {"Charlie", 78}};    std::sort(students.begin(), students.end(), compareByScore);    for (const auto& s : students) {        std::cout << s.name << ": " << s.score << std::endl;    }    return 0;}

使用Lambda表达式(推荐)

Lambda让代码更简洁,尤其适合临时排序逻辑。可以直接在std::sort调用中写比较逻辑。

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

示例:按名字字母顺序升序排序

std::sort(students.begin(), students.end(),     [](const Student& a, const Student& b) {        return a.name < b.name;    });

支持多条件排序,比如先按成绩降序,成绩相同时按名字升序:

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;    });

使用函数对象(仿函数)

当排序逻辑较复杂或需要复用时,可定义函数对象。

struct CompareStudent {    bool operator()(const Student& a, const Student& b) const {        return a.score < b.score; // 升序    }};// 使用方式std::sort(students.begin(), students.end(), CompareStudent{});

注意事项与技巧

确保比较函数满足“严格弱序”规则,即:

对于任意a,cmp(a, a)必须为false如果cmp(a, b)为true,则cmp(b, a)应为false若cmp(a, b)cmp(b, c)为true,则cmp(a, c)也应为true

避免在比较中使用==,这会导致排序行为未定义。

对基本类型如intdouble的vector,也可用自定义规则,比如逆序排列:

std::vector nums = {3, 1, 4, 1, 5};std::sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });

基本上就这些。掌握函数指针、Lambda和仿函数三种方式,就能应对大多数自定义排序场景。日常开发中,Lambda最常用,也最直观。注意保持比较逻辑清晰,避免副作用。

以上就是c++++中如何自定义排序规则排序vector_c++ vector自定义排序技巧的详细内容,更多请关注创想鸟其它相关文章!

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

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 01:39:28
下一篇 2025年12月19日 01:39:46

相关推荐

发表回复

登录后才能评论
关注微信