这道题根据两种情况编写不同的比较函数就可以完成
#include <iostream>
#include <algorithm>
using namespace std;
class student {
public:
string name;
int grade;
int i; //记录输入序号
void studentinit(string a, int b,int c) {
this->name = a;
this->grade = b;
this->i = c;
}
};
student h[1000];
bool compare_1(student a, student b) { //排序函数1,降序
if (a.grade == b.grade)
return a.i < b.i;
else {
return a.grade < b.grade;
}
}
bool compare_0(student a, student b) { //排序函数2,升序
if (a.grade == b.grade)
return a.i < b.i;
else {
return a.grade > b.grade;
}
}
int main()
{
int n,m;
while (cin >> n >> m) { //这里比较坑,需要是循环输入
string a;
int b;
for (int i = 0; i < n; i++) {
cin >> a >> b;
h[i].studentinit(a, b, i);
}
if (m) sort(h, h + n, compare_1);
else sort(h, h + n, compare_0);
for (int i = 0; i < n; i++) {
cout << h[i].name << " " << h[i].grade << endl;
}
}
}