C++結構體多級排序的三種方法
阿新 • • 發佈:2018-11-10
C++結構體多級排序的三種方法
struct node{
int chinese,math;
char name[15];
};
需求:按數學成績從大到小排序
1.自定義比較器
//自定義比較函式
bool cmp(node a,node b){
return a.math>b.math;
}
2.定義友元函式
struct node{ int chinese,math; char name[15]; //友元函式 friend bool operator<(node a,node b){ return a.math>b.math; } };
3.過載小於運算子
struct node{
int chinese,math;
char name[15];
//過載小於運算子
bool operator <(const node&b)const{
return math>b.math;
}
};
完整例項程式
#include <iostream> #include <cstdio> #include<algorithm> using namespace std; #define INF 0x3f3f3f3f const int maxn = (1e5+10); struct node{ int chinese,math; char name[15]; /* //過載小於運算子 bool operator <(const node&b)const{ return math>b.math; } */ //友元函式 friend bool operator<(node a,node b){ return a.math>b.math; } }; node arr[maxn]; //自定義比較函式 bool cmp(node a,node b){ return a.math>b.math; } int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int lcm(int a,int b) { return a/gcd(a,b)*b; } int main() { int n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d%d%s",&arr[i].chinese,&arr[i].math,arr[i].name); } sort(arr,arr+n); printf("%d\n%s\n",lcm(arr[0].chinese,arr[1].chinese),arr[0].name); } /* 3 50 60 張三 40 80 李四 45 100 王五 */