C++ primer 第十章参考答案 10.9

本文提供两种使用C++实现的方法来统计输入文本中各个单词出现的次数,并输出统计结果。方法一利用标准map直接计数,方法二则通过insert操作及pair类型的返回值实现。
 

习题10.9   编写程序统计并输出所读入的单词出现的次数

方法一:

#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int main()
{
   map<string,int> word_count;
 string word;
 while(cin>>word)
 {
 
  ++word_count[word];
 }
 for(map<string,int>::iterator map_it = word_count.begin();map_it!=word_count.end();++map_it)
  cout<<map_it->first<<" "<<map_it->second<<endl;
 

 cout<<endl;
 return 0;
}

方法二:

#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int main()

 map<string,int> word_count;
 string word;
 while(cin>>word)
 {
  pair<map<string,int>::iterator,bool> p = word_count.insert(make_pair(word,1));

  /*

 

p为pair类型变量,第一个元素为map<string,int>容器的迭代器,第二个元素为bool类型。insert操作在word_count容器中加入一个键为string word,值为int 1的对象;insert操作返回pair赋给p,则p的第一个元素迭代器指向的键为string word,且当word在word_count中不存在时p的第二个元素为true,存在时为false。后面的语句if(p.second == false)即判断当word在word_count中存在时,执行if语句内操作。

 

*/
  if(p.second==false)
  {
  
   ++p.first->second;

/*

可理解为:

++(*(p.first).second);

p.first为指向word_count容器内键为string word对象的迭代器,对其解引用得到word_count容器内键为string word的对象,该对象类型为map<string,int>::valut_type。value_type为pair类型,对该对象执行.second得到第二个元素类型为int,在该程序内即为word出现的数量。最后对该int类型的第二元素执行自增操作。

 

*/
  }
 
 }
 for(map<string,int>::iterator map_it = word_count.begin();map_it!=word_count.end();++map_it)
  cout<<map_it->first<<" "<<map_it->second<<endl;
 

 cout<<endl;
 return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值