sort 使用需#include<algorithm>
sort函數的3個參數:
1.需要排序數組的起始地址
2.需要排序數組的結束地址
3.排序函數 (若不寫排序函數,默認為整數的從小到大排序)
sort(arr,arr+n,cmp);
對結構體排序的使用方法:
有一個node類型的數組node arr[100],想對它進行排序:
1.先按a值升序排列
2.如果a值相同,再按b值降序排列
3.如果b還相同,就按c升序排列。
就可以寫這樣一個比較函數:
struct node{ int a; int b; double c; }; bool cmp(node x,node y){ if(x.a!=y.a) return x.a>y.a; if(x.b!=y.b) return x.b>y.b; return x.c<y.c; }
例:給出n個學生的成績,將這些學生按成績排序,排序規則:總分高的在前;總分相同,數學成績高的在前;總分與數學相同,英語高的在前;總分數學英語都相同,學號小的在前
輸入格式
第一行一個正整數n,表示學生人數
接下來n行每行3個0~100的整數,第i行表示學號為i的學生的數學、英語、語文成績
接下來n行每行3個0~100的整數,第i行表示學號為i的學生的數學、英語、語文成績
輸出格式
輸出n行,每行表示一個學生的數學成績、英語成績、語文成績、學號
按排序后的順序輸出
按排序后的順序輸出
樣例輸入
2
1 2 3
2 3 4
1 2 3
2 3 4
樣例輸出
2 3 4 2
1 2 3 1
1 2 3 1
#include <iostream> #include <stdlib.h> #include <math.h> #include <string.h> #include <algorithm> using namespace std; int n,m; int ans=0; bool vis[105]; int dp[105],aa[105]; struct node{ int id; int math; int eglish; int chinese; int all; }; bool cmp(node x,node y){ if(x.all!=y.all) return x.all>y.all; if(x.math!=y.math) return x.math>y.math; if(x.eglish!=y.eglish) return x.eglish>y.eglish; return x.id<y.id; } int main() { node arr[105]; cin>>n; node stu; for(int i=0;i<n;i++){ stu.id=i+1; cin>>stu.math>>stu.eglish>>stu.chinese; stu.all=stu.math+stu.eglish+stu.chinese; arr[i]=stu; } sort(arr,arr+n,cmp); for(int i=0;i<n;i++){ cout<<arr[i].math<<" "<<arr[i].eglish<<" "<<arr[i].chinese<<" "<<arr[i].id<<endl; } return 0; }