c++从大到小排序的不同方法介绍

在C++中,有多种方法可以实现从大到小的排序。下面将详细介绍一些常用的方法:

  1. 使用自定义比较函数:
    这是最常见的方法之一,使用std::sort函数并传入自定义的比较函数,使得排序按照从大到小的顺序进行。示例如下:

    #include
    #include
    #include

    bool compare(int a, int b) {
    return a > b; // 以从大到小的顺序进行排序
    }

    int main() {
    std::vector vec = {5, 2, 8, 3, 1};

    复制代码
     std::sort(vec.begin(), vec.end(), compare);
    
     // 输出排序结果
     for (auto num : vec) {
         std::cout << num << " ";
     }
     std::cout << std::endl;
    
     return 0;

    }

  2. 使用lambda表达式:
    lambda表达式是一种匿名函数,可以在代码中内联定义比较函数,更加简洁。示例如下:

    #include
    #include
    #include

    int main() {
    std::vector vec = {5, 2, 8, 3, 1};

    复制代码
     std::sort(vec.begin(), vec.end(), [](int a, int b) {
         return a > b; // 以从大到小的顺序进行排序
     });
    
     // 输出排序结果
     for (auto num : vec) {
         std::cout << num << " ";
     }
     std::cout << std::endl;
    
     return 0;

    }

  3. 使用自定义的仿函数(Functor):
    仿函数是一种重载了函数调用操作符()的对象,可以被当作普通函数使用。通过自定义一个仿函数,实现从大到小的排序。示例如下:

    #include
    #include
    #include

    struct Compare {
    bool operator()(int a, int b) const {
    return a > b; // 以从大到小的顺序进行排序
    }
    };

    int main() {
    std::vector vec = {5, 2, 8, 3, 1};

    复制代码
     std::sort(vec.begin(), vec.end(), Compare());
    
     // 输出排序结果
     for (auto num : vec) {
         std::cout << num << " ";
     }
     std::cout << std::endl;
    
     return 0;

    }

以上是三种常用的从大到小排序的方法,它们都使用了std::sort函数,但是在比较函数上有所不同。你可以根据自己的需求选择适合的方法来排序。无论哪种方法,都可以实现按从大到小的顺序对容器进行排序。

相关推荐
keyipatience2 分钟前
5种IO模型与阻塞IO,select,poll,epoll,LT和ET模式
linux·服务器·网络·数据结构·c++·算法
汉克老师4 分钟前
CSP-J 初赛(以满分为目标):第三十八课《数学与逻辑①——排列还是组合?先搞清楚“选”与“排”》
c++·csp-j·小学生·学c++编程
qeen877 分钟前
【C++】智能指针介绍
开发语言·c++·笔记·指针
Lionel_Coder11 分钟前
matmul 总体设计
c++
hanchenxing13 分钟前
本地AI绘画网关: 用 30 行 Python 把 NVIDIA FLUX.2 Klein 接入 OpenAI 兼容客户端Python
开发语言·python·ai作画·ai绘画·nvidia
Dream Cosmos19 分钟前
C++ 中 static 关键字的作用与使用规则
linux·c++
路径规划6661 小时前
(MATLAB代码) 船舶轨迹聚类:K-means 算法(260912)
算法·matlab·kmeans
PHP实战开发录2 小时前
PHP脚本手动能跑定时任务却失败
开发语言·php·开发
蒸蒸yyyyzwd3 小时前
cpp 选手秋招学习笔记 day33
c++·笔记·求职招聘
郝学胜-神的一滴3 小时前
Effective Python 条款 10 :海象运算符_=
开发语言·python·程序人生·开源