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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值