题目
成绩排序——2000年清华大学计算机机试真题
代码
1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 using namespace std; 5 typedef struct stu{ 6 char name[101]; 7 int age; 8 int score; 9 }stu; 10 bool comp(stu a,stu b){ 11 if(a.score != b.score) return a.score < b.score; 12 else{ 13 if(a.name != b.name){ 14 return a.name < b.name; 15 } 16 else{ 17 return a.age < b.age; 18 } 19 20 } 21 } 22 int main(){ 23 stu s[1010]; 24 int n; 25 while(scanf("%d",&n) != EOF){ 26 for(int i = 0 ;i < n;i++){ 27 scanf("%s%d%d",&s[i].name,&s[i].age,&s[i].score); 28 } 29 sort(s,s+n,comp); 30 for(int i = 0;i < n;i++){ 31 printf("%s %d %d ",s[i].name,s[i].age,s[i].score); 32 } 33 puts(""); 34 } 35 }
在结构体中重载小于运算符
1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 using namespace std; 5 typedef struct stu{ 6 char name[101]; 7 int age; 8 int score; 9 bool operator<(const stu &b) const{ 10 if(score != b.score) return score < b.score; 11 else{ 12 if(name != b.name){ 13 return name < b.name; 14 } 15 else{ 16 return age < b.age; 17 } 18 19 } 20 } 21 }stu; 22 23 int main(){ 24 stu s[1010]; 25 int n; 26 while(scanf("%d",&n) != EOF){ 27 for(int i = 0 ;i < n;i++){ 28 scanf("%s%d%d",&s[i].name,&s[i].age,&s[i].score); 29 } 30 sort(s,s+n); 31 for(int i = 0;i < n;i++){ 32 printf("%s %d %d ",s[i].name,s[i].age,s[i].score); 33 } 34 puts(""); 35 } 36 }