风清扬zld的博客

此刻正当修行时

第十章:单词出现次数程序

//通过建立map对象保存所读入的单词及其出现次数;
//统计并输出所读入的单词出现的次数;
//使用insert函数代替下标操作
#include <iostream>
#include <map>
#include <utility>
#include <string>
using namespace std;
int main()
{
map<string,int> wordCount;
string word;
//读入单词并统计其出现的次数
cout<<"enter some words(Ctrl+Z to end):"<<endl;
while(cin>>word)
{
//插入元素<word,1>
pair<map<string,int>::iterator,bool> ret=wordCount.insert(make_pair(word,1));
if(!ret.second)//该单词已在容器中存在
++ret.first->second;//将该单词出现的次数加1


}
//输出结果
cout<<"word\t\t"<<"times"<<endl;
for(map<string,int>::iterator iter=wordCount.begin();iter!=wordCount.end();++iter)
cout<<(*iter).first<<"\t\t"<<(*iter).second<<endl;


//用map对象的迭代遍历输出单词以及它出现的次数
map<string,int>::const_iterator map_it=wordCount.begin();
while(map_it!=wordCount.end())
{
cout<<map_it->first<<"  occurs  "<<map_it->second<<" times "<<endl;
++map_it;
}
return 0;

}


//通过建立map对象保存所读入的单词及其出现次数;
//统计并输出所读入的单词出现的次数;

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string,int> wordCount;
string word;
cout<<"enter some words(Ctrl+Z to end):"<<endl;
while(cin>>word)
++wordCount[word];
cout<<"word\t\t"<<"times"<<endl;
for(map<string,int>::iterator iter=wordCount.begin();iter!=wordCount.end();++iter)
cout<<(*iter).first<<"\t\t"<<(*iter).second<<endl;
return 0;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zuolindian/article/details/46809157
个人分类: 习题程序
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭