【算法競賽模板1】結構體排序
0.總結
Get to the points firstly, the article comes from LawsonAbs!
- 實現對結構體的排序
1.代碼
1.1主要代碼
- 定義一個結構體
//新建一個student 結構體,用於保存student的信息
struct student
{
int height;
char name[10];
};
- 實現排序
//比較函數,對結構體進行排序
int cmp(student s1,student s2){
if(s1.height!=s2.height){
return s1.height > s2.height;
}
else if(s1.height == s2.height){
return strcmp(s1.name,s2.name) < 0;
}
}
1.2 完整代碼
#include<cstdio>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;
//新建一個student 結構體,用於保存student的信息
struct student
{
int height;
char name[10];
};
//比較函數,對結構體進行排序
int cmp(student s1,student s2){
if(s1.height!=s2.height){
return s1.height > s2.height;
}
else if(s1.height == s2.height){
return strcmp(s1.name,s2.name) < 0;
}
}
int main(){
int number;//the total number of people
int k;//the total number of rows
char name[10];
student stu[10];
int height;
scanf("%d%d",&number,&k);
printf("number = %d,k = %d\n",number,k);
int i = 0;
for(i = 0;i < number ;i++){
scanf("%s %d",&stu[i].name,&stu[i].height);
}
sort(stu,stu+number,cmp);
printf("=======after sort=======\n");
for(i = 0;i< number;i++){
printf("name = %s,height = %d\n",stu[i].name,stu[i].height);
}
return 0;
}
/*
10 3
Tom 188
Mike 170
Eva 168
Tim 160
Joe 190
Ann 168
Bob 175
Nick 186
Amy 160
John 159
*/
其中的cmp
函數爲自定義排序規則,而底層調用的排序函數是sort
。具體的sort
和qsort
見網上的博客,這裏不再贅述。