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;
}