【算法競賽模板1】結構體排序

【算法競賽模板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。具體的sortqsort 見網上的博客,這裏不再贅述。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章