思路:使用两次map进行计数和排序,第一次map用来统计不同的单词出现的次数。注意最后一个单词要把'.'去掉,大写的字母要转换成小写的字母。
第二次的multimap用来将单词出现的次数按照降序排列,因为出现次数可能会有重复的所以这里使用multimap。同时降序排序需要回传一个仿函数greater
#include <iostream>
#include <string>
#include <map>
#include <functional>
using namespace std;
void to_uppercase(string& s)
{
for( auto& e : s)
{
if(e >= 'A' && e <='Z')
{
e += 32;
}
}
}
int main()
{
string s;
map<string,int> countmap;
while( cin>> s)
{
if(s.back() == '.')
s.pop_back();
to_uppercase(s);
countmap[s]++;
}
multimap<int,string,greater<int>> sortmap;
for(auto& e : countmap)
{
sortmap.insert(make_pair(e.second,e.first));
}
auto it = sortmap.begin();
while(it != sortmap.end())
{
cout<<it->second<<":"<<it->first<<endl;
it++;
}
}

京公网安备 11010502036488号