题目描述
输入 nn 个同学的姓名及对应的考试成绩,请你按照成绩从大到小进行排序后输出。
输入格式
第一行,一个整数 n,(其中n≤100)
接下来的n行,每行是一个同学的姓名和成绩,姓名和成绩之间用一个空格隔开。
(每个同学的成绩都不相同)
输出格式
共n行,按照成绩从大到小排序后的姓名和成绩,姓名和成绩之间用一个空格隔开。
输入样例
5
Peter 65
Anny 98
Dora 95
Lily 87
Cook 100
输出样例
Cook 100
Anny 98
Dora 95
Lily 87
Peter 65
有用请点采纳
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
typedef pair<string, int> PAIR;
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.second > rhs.second;
}
};
int main(){
int n, score; // 输入人数
string name;
cin >> n;
map<string, int> name_score_map;
// 输入
for (int i = 0; i < n; i++){
cin >> name >> score;
name_score_map[name] = score;
}
vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
for (int i = 0; i != name_score_vec.size(); ++i) {
cout<<name_score_vec[i].first<<" "<<name_score_vec[i].second<<endl;
}
return 0;
}