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

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

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

    #include <iostream>
    #include <vector>
    #include <algorithm>

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

    int main() {
    std::vector<int> 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 <iostream>
    #include <vector>
    #include <algorithm>

    int main() {
    std::vector<int> 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 <iostream>
    #include <vector>
    #include <algorithm>

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

    int main() {
    std::vector<int> 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函数,但是在比较函数上有所不同。你可以根据自己的需求选择适合的方法来排序。无论哪种方法,都可以实现按从大到小的顺序对容器进行排序。

相关推荐
mit6.8244 分钟前
dfs|bfs|定长栈|栈+双指针
算法
赵财猫._.1 小时前
Native API开发:C++与ArkTS混合编程实战
开发语言·c++·harmonyos
普通网友1 小时前
基于C++的操作系统开发
开发语言·c++·算法
狂团商城小师妹2 小时前
JAVA外卖霸王餐CPS优惠CPS平台自主发布小程序+公众号霸王餐源码
java·开发语言·小程序
2501_941111342 小时前
C++中的策略模式高级应用
开发语言·c++·算法
心软小念3 小时前
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍
java·开发语言·python
wearegogog1233 小时前
时间分数阶微分方程数值求解
算法
CoderYanger4 小时前
A.每日一题——2536. 子矩阵元素加 1
java·线性代数·算法·leetcode·矩阵
sanggou4 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友4 小时前
C++与Qt图形开发
开发语言·c++·算法