C/C++ 刷题模板介绍

版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/86549083

C/C++ 刷题模板

1.

2.代码

2.1
  • 实现排序功能
#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 见网上的博客,这里不再赘述。

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/86549083