


分析和思路:
把成绩保存到map或者vector中,然后进行排序。这道题关键是处理那个成绩相等时,排序后依然保持相对顺序不变的问题,费了好大的心思,发现效果依然不是自己想要的,写出的代码如下:
1 #include "iostream"
2 #include
3 #include
想通过vector元素的顺序来确定map中元素的顺序,但是依然是map自动排序了。
解决办法:使用稳定排序stable_sort,改进后的代码如下:
1 #include
2 #include <string>
3 #include
4 #include
5 //#include
6 using namespace std;
7
8 bool cmp0(const pair<string,int> &a,const pair<string,int> &b)
9 {
10 return a.second>b.second;
11 }
12
13 bool cmp1(const pair<string,int> &a,const pair<string,int> &b)
14 {
15 return a.second<b.second;
16 }
17
18 void mysort(int n,int flag)
19 {
20 //unordered_map res;
21 vectorstring,int>> res(n);
22 for(int i=0;i)
23 {
24 cin>>res[i].first>>res[i].second;
25 }
26 if(flag==0)
27 {
28 stable_sort(res.begin(),res.end(),cmp0);
29 }
30 else if(flag==1)
31 {
32 stable_sort(res.begin(),res.end(),cmp1);
33 }
34
35 for(int i=0;i)
36 {
37 cout<" "<endl;
38 }
39 }
40
41 int main()
42 {
43 int n,flag;
44 while(cin>>n>>flag)
45 {
46 mysort(n,flag);
47 }
48 return 0;
49 }
总结:这个程序言简意赅,非常高效,值得借鉴和学习。pair这个结构作用挺好,对vector和map都适用,注意它的用法。