sort函数实现结构体排序

P1068 分数线划定

结构体排序,外加一个检查同分用的循环

#include
#include
#include
using namespace std;
struct student 
{
	int num;
	int score;
};

//需要向sort函数传入的比较函数
bool comparison(student a,student b){
	if(a.score==b.score) return a.num<b.num;
	//如果分数相同则按号码升序排列
	else return a.score>b.score;
	//如果分数不同则按分数降序排列
}

int main()
{
	int n;
	student stu[5005];
	double line_rank,m;
	scanf("%d%lf",&n,&m);
	line_rank=floor(m*1.5);
	//ceil向上取整,floor向下取整(这道题直接强制int型也行)
	for(int i=1;i<=n;i++){
		scanf("%d %d",&stu[i].num,&stu[i].score);
	}
	//涉及具体个数的还是把下标0抛弃吧
	sort(stu+1,stu+n+1,comparison);
	//因为抛弃了下标0,此处要记得+1;
	int ans=0;
	for(int i=1;i<=line_rank;i++) ans++;
	//ans记录基本录取人数
	for(int i=line_rank+1;i<=n;i++){
		if(stu[i].score==stu[ans].score) ans++;
	}
	//向下面检查是否还有和分数线同分的,有则加上
	printf("%d %d\n",stu[ans].score,ans);
	//输出分数线和实际录取人数
	for(int i=1;i<=ans;i++){
	printf("%d %d\n",stu[i].num,stu[i].score);
	}
	return 0;
}

你可能感兴趣的:(sort函数实现结构体排序)