liulunet

成长记录

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

map容器中含有一个或一对迭代器形参的insert函数版本并不说明是否有或有多少个元素插入到容器中,而单个参数版本中则会返回pair类型对象:

 

m.insert(e)  e是一个用在m上的value_type类型的值。如果键(e.first)不在m中,则插入一个值为e.second的新元素;如果该键在m中已存在,则保持m不变。该函数返回一个pair类型对象,包含指向键为e.first的元素的map迭代器,以及一个bool类型的对象,表示是否插入了该元素。

 

感觉这里insert的使用比较难懂,记下以免忘记

 

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

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
	string word;
	map<string,int> word_count;

	while(cin >> word)
	{
		pair<map<string,int>::iterator,bool> p = word_count.insert(make_pair(word,1));
		if(p.second == false)
		{
			++p.first->second;
		}
	}

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

 

分析:

 

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语句内操作。

 

++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类型的第二元素执行自增操作。

posted on 2011-06-04 15:34  liulunet  阅读(3793)  评论(0编辑  收藏  举报