一、必备sort():

#include<algorithm>
using namespace std;
void sort (first, last, cmp);
// first 首元素地址;last 尾元素地址下一个地址;cmp 比较函数

二、结构体:

struct Student {
   
    char name[10];
    char id[10];
    int score[4];
    int rank[4];
int best;
}stu[10000];

三、cmp函数:

bool cmp (Student a,Student b){
   
	if(a.score!=b.score)
	return a.score>b.score;
	else  return strcmp(a.name,b.name)<0;
}

四、排名的实现

分数不同排名不同,相同占用一个排名的位置

弟一种方法:记录在结构体(rank)属性中:
  • ①将第一个对象的该属性设置为1
  • ②遍历剩余对象的该属性,若相等就设置为一样,否则就在上一个的基础上+1.
		stu[0].rank=1;
	for(int i=1;i<n;i++){
   
		if(stu[i].score==stu[i-1].score){
   
			stu[i].rank=stu[i-1].rank;
		}else{
   
			stu[i].rank=i+1;
		}
	}

第二种方法:直接输出:

有时候不一样需要真的把排名记录下来,而是直接输出即可。

		int rank=1;
	for(int i=0;i<n;i++){
   
		if(i>0&&stu[i].score!=stu[i-1].score){
   
			rank=i+1;
		}
		cout<<rank;
	} 

1012 The Best Rank (25)

1083 List Grades (25分)