C++STL sort函数

头文件:

#include<algorithm>//sort头文件

几种排序准则实例:

bool cmp1(int x,int y){
    return x>y;//从小到大进行排序
}
bool cmp2(int x,int y){
    return x%10>y%10;
}
bool cmp3(node x,node y){
    if(x.a!=y.a){
        return x.a<y.a;
    }
    return x.b<y.b;
}
bool cmp4(node x,node y){
    int aa=x.a+x.b;
    int bb=y.a+y.b;
    return aa>bb;
}

完整代码:

#include<iostream>
#include<algorithm>//sort头文件
using namespace std;
const int n=5;
struct node{
    int a,b;
    string str;
}ch[10];

bool cmp1(int x,int y){
    return x>y;//从小到大进行排序
}
bool cmp2(int x,int y){
    return x%10>y%10;
}
bool cmp3(node x,node y){
    if(x.a!=y.a){
        return x.a<y.a;
    }
    return x.b<y.b;
}
bool cmp4(node x,node y){
    int aa=x.a+x.b;
    int bb=y.a+y.b;
    return aa>bb;
}

int main(){
    int i,j,k;
    for(i=1;i<=n;i++)cin>>ch[i].a;
    sort(ch+1,ch+1+n,cmp3);//注意是ch+1
    for(i=1;i<=n;i++)cout<<ch[i].a<<endl;

    return 0;
}

The end!

猜你喜欢

转载自blog.csdn.net/Cat_ind/article/details/129409784