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

相关推荐
冷崖1 天前
原子锁操作
c++·后端
旖旎夜光1 天前
C++(17)
c++·学习
Larry_Yanan1 天前
Qt多进程(三)QLocalSocket
开发语言·c++·qt·ui
醒过来摸鱼1 天前
Java classloader
java·开发语言·python
superman超哥1 天前
仓颉语言中元组的使用:深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
小鸡吃米…1 天前
Python - 继承
开发语言·python
JIngJaneIL1 天前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
祁思妙想1 天前
Python中的FastAPI框架的设计特点和性能优势
开发语言·python·fastapi
LYFlied1 天前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠1 天前
rust自动调用Deref(deepseek)
开发语言·算法·rust