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

相关推荐
得物技术18 分钟前
得物推荐系统诊断 Agent:从 “调接口” 到 “会思考”|AICon 演讲整理
人工智能·算法·架构
Lugas26 分钟前
为啥说男生找对象尽量在25岁前找到?
算法
北冥you鱼27 分钟前
Go语言与默克尔树:区块链数据完整性的基石
开发语言·golang·区块链
MrZhao40029 分钟前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
库克克37 分钟前
【C++】类和对象--this指针详解
java·开发语言·c++
ch0sen1pm1 小时前
加班之余从零写了个 spdlog 风格的日志库
c++
JackieZhengChina1 小时前
image-viewer-js 开源图片查看插件完整教程
开发语言·javascript·开源
QN1幻化引擎1 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
吃着火锅x唱着歌1 小时前
Effective C++ 学习笔记 条款33 避免遮掩继承来的名称
c++·笔记·学习
光影少年1 小时前
react的View/Text/Image/ScrollView 常用组件注意事项
开发语言·前端·javascript·react.js·前端框架