c++ cmp 指定排序规则

c++ cmp 指定排序规则

vector排序,从大到小指定规则。

#include <iostream>
#include <algorithm>
#include <vector>
bool cmp(int a ,int b){
    return a>b;
}

int main(){
  
    vector<int >vec={1,4,6,7,8,9,0,0};
    sort(vec.begin(),vec.end(),cmp);//使用逻辑函数
    for (int i = 0; i < vec.size(); ++i) {
        cout<<vec[i]<<endl;
    }
    return 0;
    }

结构体指定成员变量排序规则。

例子:有N个学生的数据,将学生数据按成绩高低排序,如果成绩相同则按姓名字符的字母序排序,如果姓名的字母序也相同则按照学生的年龄排序,并输出N个学生排序后的信息(都是从大到小)

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

struct student{
    int grade;
    char name[20];
    int age;
};

bool cmp(student a,student b){
    int t = strcmp(a.name,b.name);
    if(a.grade != b.grade)
        return a.grade > b.grade;
    else if(t != 0)
        return t > 0;
    else
        return a.age > b.age;
}

int main(){
    student stu[5]={{98,"frank",15},{96,"frtgg",15},{78,"asfffas",13},{87,"sifhsh",17},{87,"sifhsh",16}};
    sort(stu,stu+5,cmp);
    for (int i = 0; i < 5;i++){
        cout<<stu[i].grade<<" "<<stu[i].name<<" "<<stu[i].age<<" "<<endl;
   }
    return 0;

}

上面两个例子的cmp都可以用匿名函数直接卸写在sort第三个参数上。

#include <iostream>
#include <algorithm>
#include <vector>

int main(){
    vector<int >vec={1,4,6,7,8,9,0,0};
    sort(vec.begin(),vec.end(),[](int a,int b){
        return a<b;
    });//匿名函数,[]内是引用其他的外面的变量
    
    for (int i = 0; i < vec.size(); ++i) {
        cout<<vec[i]<<endl;
    }
    return 0;
    }
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

struct student{
    int grade;
    char name[20];
    int age;
};


int main(){
    student stu[5]={{98,"frank",15},{96,"frtgg",15},{78,"asfffas",13},{87,"sifhsh",17},{87,"sifhsh",16}};//初始化
    
    sort(stu,stu+5,[](student a,student b){//匿名函数
        int t = strcmp(a.name,b.name);
        if(a.grade != b.grade)
            return a.grade > b.grade;
        else if(t != 0)
            return t > 0;
        else
            return a.age > b.age;
    });
    
    for (int i = 0; i < 5;i++){//输出
        cout<<stu[i].grade<<" "<<stu[i].name<<" "<<stu[i].age<<" "<<endl;
   }
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

moletop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值