Bootstrap

自定义比较函数 down 作为 sort 函数的参数实现数组元素从大到小排序

【自定义比较函数 down 作为 sort 函数的参数实现数组元素从大到小排序】

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e3+5;
int a[maxn];

bool down(int u,int v) {
    return u>v;
}

int main() {
    int n;
    cin>>n;
    for(int i=0; i<n; i++) cin>>a[i];
    sort(a,a+n,down);
    for(int i=0; i<n; i++) cout<<a[i]<<" ";
}

/*
in:
5
6 1 3 8 5

out:
8 6 5 3 1
*/


另外一种解决方案是利用 sort(a,a+n,greater<int>());对数组 a 的 n 个元素从大到小排序。
详见:
https://blog.csdn.net/hnjzsyjyj/article/details/144239572



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/144239572


 

;