#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
// map按照value排序
// 按照單詞出現個數排序
// 因為sort函數支持順序容器,不支持關聯容器的排序,所以要將map放進順序容器里面
int cmp(const pair<string,int> &PairIt1, const pair<string, int> &PairIt2)
{
return PairIt1.second > PairIt2.second;
}
int main()
{
map<string, int> map1;
string str;
cout << "輸入單詞:"<<endl;
while (cin >> str)
{
pair<map<string,int>::iterator,bool> ret= map1.insert(make_pair(str,1));
if(!ret.second) // 插入失敗,表示有重復的值,所以map中的int要自增
{
++ret.first->second;
}
// map1[str]++; // 注意它和insert的差別
if(cin.get() == '\n')
break;
}
// 將map存入vector中
vector<pair<string,int> > vec;
for(auto it = map1.begin(); it != map1.end(); it++)
{
vec.push_back(make_pair(it->first,it->second));
}
sort(vec.begin(),vec.end(), cmp);
for(auto it = 0; it < vec.size(); it++)
{
cout << vec[it].first << " " << vec[it].second << endl;
}
return 0;
}
// 測試數據
// aa bb cc dd aa cc cc cc
//cc 4
//aa 2
//bb 1
//dd 1