紧接上一段小程序,要求程序在输出时应该对全部的单词分组,即首先输出出现一次的,然后是出现两次的,以此类推。这是Accelarated C++练习题7-1:
#include <map>
#include <vector>
#include <iostream>
#include <string>
using std::string;
using std::map;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
int _tmain(int argc, _TCHAR* argv[])
{
string word;
map<string,int> counters;
map<int,vector<string> > group_counters; //将单词按出现次数分组
cout<<"Please input words(Ctrl+z to end):"<<endl;
while (cin>>word)
++counters[word];
for (map<string,int>::const_iterator iter = counters.begin();iter != counters.end();iter++)
group_counters[iter->second].push_back(iter->first);
for (map<int,vector<string> >::const_iterator iter = group_counters.begin();iter != group_counters.end();iter ++) {
for (vector<string>::const_iterator it = iter->second.begin();it != iter->second.end();it++)
cout<<*it<<"\t"<<iter->first<<endl;
}
return 0;
}