您的位置:首页 > 编程语言 > C语言/C++

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

2011-08-19 10:40 197 查看
习题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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: