题解 | #成绩排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
使用map<int,string>,插入后根据int作为key值来自动排好序,string为每次插入之后在后面增加新的名字,以保证最后可以按照插入的顺序来输出:
auto iter = myMap.find(score);
if (iter == myMap.end())
myMap.insert(pair<int, string>{score, name});
else
{
iter->second += " ";
iter->second += name;
}全部程序:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <map>
#include <list>
using namespace std;
int main()
{
int num;
while (cin >> num)
{
int flag;
cin >> flag;
map<int, string> myMap;
for (int i = 0; i < num; i++)
{
string name;
int score;
cin >> name;
cin >> score;
auto iter = myMap.find(score);
if (iter == myMap.end())
myMap.insert(pair<int, string>{score, name});
else
{
iter->second += " ";
iter->second += name;
}
}
if (flag)
{
for (auto i : myMap)
{
stringstream ss;
ss << i.second;
string strTemp;
while (ss>>strTemp)
{
cout << strTemp << ' ' << i.first << endl;
}
}
}
else
{
auto i = myMap.rbegin();
while(i!=myMap.rend())
{
stringstream ss;
ss << i->second;
string strTemp;
while (ss >> strTemp)
{
cout << strTemp << ' ' << i->first << endl;
}
i++;
}
}
}
return 0;
}
