自定义数据类型 根据例题讲解
例1 分数排序学号优先
#include <iostream>
#include<cstdio>
#include<algorithm>
struct Student{
int number;
int score;
/*
bool operator< (Student student) const{
if(score == student.score){
return number < student.number;
}else{
return score < student.score;
}
}
sort(arr,arr+n);
*/
}
bool Compare(Student x,Student y){
if(x.score == y.score){
return x.number < y.number;
}else{
return x.score < y.score;
}
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;++i){
scanf("%d%d",&arr[i].number,&arr[i].score);
}
sort(arr,arr+n,Compare);
for(int i=0;i<n;++i){
printf("%d %d\n",arr[i].number,arr[i].score);
}
return 0;
}
例2 奇数偶数排序,分别由小到大,奇数优先。
bool Compare(int x,int y){
if(x%2==1 && y%2==1){
return y < x;
}else if(x%2==0 && y%2==0){
return x < y;
}else if(x%2==1 && y%2==0){
return true;
}else{
return false;
}
}
原理就是,定义大小,使之可以比较。