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

相关推荐
殇淋狱陌几秒前
【初始Python】Python学习基础(数据类型、定义、变量、下标、目前的开发语言对比)
开发语言·python·学习
lsx2024062 分钟前
Ruby 迭代器
开发语言
史迪仔01124 分钟前
[QML] Popup 与 Dialog
开发语言·前端·javascript·c++·qt
John.Lewis5 分钟前
C++加餐课-stack_queue:计算器-逆波兰表达式
开发语言·c++
DeepModel5 分钟前
通俗易懂讲透 Mini-Batch K-means
开发语言·人工智能·机器学习·kmeans·batch
happy_baymax6 分钟前
基于正弦波直接移相的PSFB控制方法
开发语言
傻啦嘿哟6 分钟前
如何用 Python 拆分 Word 文件:高效分割大型文档的完整指南
开发语言·c#
高斯林.神犇6 分钟前
五、注解方式管理bean
java·开发语言
hoiii1876 分钟前
C# 读取 CSV/Excel 文件数据至 DataGridView
开发语言·c#·excel
xiaotao1317 分钟前
01-编程基础与数学基石: 常用内置库
开发语言·人工智能·python