今日份sort“行为大赏”

:sort函数包含在头文件为#include<algorithm>的c++标准库中,调用标准库里的排序方法可以实现对数据的排序,但是sort函数是如何实现的,我们不用考虑!

sort函数的参数:

(1)第一个参数first:是要排序的数组的起始地址。

(2)第二个参数last:是结束的地址(最后一个数据的后一个数据的地址)

(3)第三个参数comp是排序的方法:可以是从升序也可是降序。如果第三个参数不写,则默认的排序方法是从小到大排序。

一、只进行初始的从大到小的数字排序

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,a[501];
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,a+n);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

二、加入第三个参数,实现特殊排序

(1)实现从大到小

#include<bits/stdc++.h>
using namespace std;
bool cmp(int a,int b){
    return a>b;
}
int main(){
    int n,a[501];
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,a+n,cmp);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

(2)字典序+大到小/小到大

#include<bits/stdc++.h>
using namespace std;
struct xs{
    string xm;
    int fs;
}a[25];
int n;
bool cmp(xs x,xs y){
    if(x.fs==y.fs) return x.xm<y.xm;
    else return x.fs>y.fs;
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i].xm>>a[i].fs;
    sort(a,a+n,cmp);
    for(int i=0;i<n;i++) cout<<a[i].xm<<" "<<a[i].fs<<endl;
    return 0;
} 
//题目链接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1178

推荐题目:http://ybt.ssoier.cn:8088/problem_show.php?pid=1177

     http://ybt.ssoier.cn:8088/problem_show.php?pid=1179

原文地址:https://www.cnblogs.com/qwn34/p/14043834.html