题解 | #成绩排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
#include<iostream>
#include<map>//最开始想把键值对存map,想法错误,因为map会自动排序key
#include<string>
#include<vector>//键值对存容器里,然后用stable_sort完成排序就可以了
#include<algorithm>
using namespace std;
using namespace __gnu_cxx;
bool cmp_val(const pair<string,int> &left,const pair<string,int> &right);
bool cmp_val2(const pair<string,int> &left,const pair<string,int> &right);
int main(){
int n;
cin >> n;
vector<pair<string,int>> score;
score.clear();//清脏数据
int type;
cin >> type;
string name;
int val;
while(n){
n--;
cin >> name >> val;
score.push_back(pair<string,int>(name,val));
}
if(type == 0){
stable_sort(score.begin(),score.end(),cmp_val2);//stable_sort是归并排序(稳定的,但效率不如快排)
}
if(type == 1){
stable_sort(score.begin(),score.end(),cmp_val);
}
for(vector<pair<string,int>> :: iterator it = score.begin(); it < score.end(); it++){
cout << it->first << " " << it->second << endl;
}
return 0;
}
bool cmp_val(const pair<string,int> &left,const pair<string,int> &right){
return left.second < right.second;
}
bool cmp_val2(const pair<string,int> &left,const pair<string,int> &right){
return left.second > right.second;
}
