PTA | 1004成绩排名 结构体,排序 一次过

64 阅读1分钟

PTA | 1004成绩排名

这道题我本来想着用pair,但是后来想想既然有姓名,学号,成绩三个元素,干脆用结构体吧.

结构体存储,再用vector的sort进行排序,因为默认sort按first排,所以我们自己写个仿函数按照成绩排,把最高的成绩排在开头,最低的成绩排在末尾,输出开头结尾成绩即可。

#include <iostream>
#include <vector>
#include <algorithm>
#include<string>
using namespace std;

struct Student
{
  string xm;
  string xh;
   int cj;
};

bool compare(const Student& a,const Student& b)
{
    return a.cj>b.cj;
}
int main()
{

    //读入到vector里面
    int n=0;cin>>n;
    vector<Student>stu(n);
    for(int i=0;i<n;i++)cin>>stu[i].xm>>stu[i].xh>>stu[i].cj;

    //排序
    sort(stu.begin(),stu.end(),compare);
   
    cout<<stu[0].xm<<" "<<stu[0].xh<<endl;
    
    cout<<stu[n-1].xm<<" "<<stu[n-1].xh<<endl;
    return 0;
}