C++中的 pair<map<string, int>::i…

int main()
{
  map<string, int> word_count;
  string word;
  while( cin >> word ){
  pair<map<string, int>::iterator, bool> ret = word_count.insert(make_pair(word,1));//能否详细解释这一步的过程?
  if( !ret.second ){
    ++ret.first->second;
  }
  }
  cout << ret.first->second << endl;
  return 0;
}

看一下你调用这个map类insert方法的原型。

pair <iterator, bool> insert(
    const value_type& _Val
);
returns a pair whose bool component returns true if an insertion was made and false if the map already contained an element whose key had an equivalent value in the ordering, and whose iterator component returns the address where a new element was inserted or where the element was already located.
也就是说,如果map中不含有_Val中的key就返回指向这个新插入节点的迭代器和true组成的pair。如果map中含有_Val中的key就返回指向这个已经存在的节点和false组成的pair。

首先你明白这个程序是统计你输入不同的单词个数的。
pair<map<string, int>::iterator, bool> ret = word_count.insert(make_pair(word,1));
这句的意思是把word和1变成pair类型,插入到word_count中。如果map中的key不含word这个字符串,就插入,并且初始化为1,因为是第一次出现,返回指向该节点的迭代器和true组成的pair。如果map中含有,就不做任何操作,返回这个已经存在的节点的迭代器和false组成的pair。 

if(!ret.second ){
    ++ret.first->second;
}
这个判断就是如果插入不成功,说明map中已经含有该单词了,但是insert处没做任何操作,在这里让统计数加1。ret.first是指向该单词key的迭代器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值