sort 函数的从大到小排序以及 ? 的运用

sort 函数位于头文件 #include <algorithm> 中,起到排序数组类型的数据结构的作用,对于从小到大排序,sort 函数的默认快排就可以做到:

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int n;
    cin >> n;
    int a[n];
    for (int i = 1;i<=n;i++){
        cin >> a[i];
    }
    sort(a+1,a+n+1);
    for (int i = 1;i<=n;i++){
        cout << a[i] << " ";
    }
    return 0;
}

  

而从大到小怎么排呢?

我们可以写一个副函数来辅助我们:

#include <iostream>
#include <algorithm>
using namespace std;
int larger(int m,int n){
    return m > n;
}
int main(){
    int n;
    cin >> n;
    int a[n];
    for (int i = 1;i<=n;i++){
        cin >> a[i];
    }
    sort(a+1,a+n+1, larger);
    for (int i = 1;i<=n;i++){
        cout << a[i] << " ";
    }
    return 0;
}

我们在sort 函数的默认排序中讲到了sort (a,a+n); 中的 a 是要排序的数组名称,至于从什么排到什么就只用将数组名称看成 0 就能知道了,比如sort (a,a+n);就是从 0 排到 n,而上述的sort(a+1,a+n+1,larger);第三个位置就是表示用什么方式来排序

至于 ? 可以用来代替 if else 来表示判断:

邓紫棋说过:“承认自己不够也是一种勇气!”

诸位道友,多多关照!

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-08 14:38:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-08 14:38:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-08 14:38:01       82 阅读
  4. Python语言-面向对象

    2024-02-08 14:38:01       91 阅读

热门阅读

  1. 精通Python中的正则表达式

    2024-02-08 14:38:01       59 阅读
  2. 贪心算法入门题(算法村第十七关青铜挑战)

    2024-02-08 14:38:01       53 阅读
  3. redis

    redis

    2024-02-08 14:38:01      57 阅读
  4. leetCode 30天

    2024-02-08 14:38:01       42 阅读
  5. 使用gpu_burn对GPU进行压测

    2024-02-08 14:38:01       50 阅读
  6. 典型数据结构的模板实现

    2024-02-08 14:38:01       56 阅读
  7. chagpt的原理详解

    2024-02-08 14:38:01       46 阅读
  8. WebGPU Inter-stage 变量

    2024-02-08 14:38:01       49 阅读
  9. watch 和 watchEffect 的使用

    2024-02-08 14:38:01       48 阅读
  10. Nginx中proxy_pass指令斜杠的作用

    2024-02-08 14:38:01       52 阅读
  11. 列出使用挂载点的进程,并结束进程 shell脚本

    2024-02-08 14:38:01       41 阅读