题解 | 成绩排序
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include <iostream>
#include <functional>
#include <string>
#include <vector>
using namespace std;
struct Student{
string name;
int score;
Student(string n, int s) : name(n), score(s) {}
Student() : name(""), score(0) {}
};
function<bool(int,int)> bigger = [](const int &a, const int &b) -> bool {return a>b;};
function<bool(int,int)> smaller = [](const int &a, const int &b) -> bool {return a<b;};
void BubbleSort(vector<Student>&stu, function<bool(int,int)> func){
int n = stu.size();
int i,j,flag;
for(i=0;i<n;i++){
flag = 0;
for(j=n-1;j>i;j--){
if(func(stu[j-1].score,stu[j].score)){
flag = 1;
auto temp = stu[j-1];
stu[j-1]= stu[j];
stu[j] = temp;
}
}
if(flag==0) break;
}
}
void PrintStu(vector<Student>stu){
for(auto i: stu){
cout<<i.name<<" "<<i.score<<endl;
}
}
int main() {
int m,mode;
while(cin>>m){
vector<Student>stu;
cin>>mode;
for(int i=0;i<m;i++){
string name;
int score;
cin >> name >> score;
stu.emplace_back(name,score);
}
if (mode==1){
BubbleSort(stu,bigger);
}else{
BubbleSort(stu,smaller);
}
PrintStu(stu);
}
}
// 64 位输出请用 printf("%lld")
