【发布时间】:2011-04-18 19:02:01
【问题描述】:
我有一个小程序,它读取一行输入并打印其中的单词,以及它们各自的出现次数。我想根据它们的出现对存储这些值的地图中的元素进行排序。我的意思是,只出现一次的单词将被排序在开头,然后出现两次的单词 7 依此类推。我知道谓词应该返回一个布尔值,但我不知道参数应该是什么。它应该是地图的两个迭代器吗?如果有人可以解释这一点,将不胜感激。提前谢谢你。
#include<iostream>
#include<map>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;
int main()
{
string s;
map<string,int> counters; //store each word & an associated counter
//read the input, keeping track of each word & how often we see it
while(cin>>s)
{
++counters[s];
}
//write the words & associated counts
for(map<string,int>::const_iterator iter = counters.begin();iter != counters.end();iter++)
{
cout<<iter->first<<"\t"<<iter->second<<endl;
}
return 0;
}
【问题讨论】: