c++_primer_exercise_1120

For the containers that have unique keys, the versions of insert and emplace that add a single element return a pair that lets us know whether the insertion happed. The first member of the pair is an iterator to the element with the given key; the second is a bool indicating whether that element was inserted, or was already there. If the key is already in the container, then insert does nothing, and bool portion of the return value is false. If the key isn't present, then the element is inserted and the bool is true.


As the code rewrited, it implements word-counting.

Look! How Crazy!!!

/**********************************************
*	IDE: vs2013
**********************************************/
#include 
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       	// for pair

int main(void)
{
	std::map
       
       
         word_count; std::string word; // version1 /* while (std::cin >> word) { ++word_count[word]; }*/ // version2, it works, but creazy!!! while (std::cin >> word) { std::pair 
         
         
           ::iterator, bool> ret = word_count.insert(std::make_pair(word, 1)); if (!ret.second) // word already in word_count { ++ret.first->second; } } std::map 
          
            ::iterator map_iter = word_count.begin(); while (map_iter != word_count.cend()) { std::cout << map_iter->first << " occurs " << map_iter->second << " times" << std::endl; ++map_iter; } return 0; } 
           
          
         
       
      
      
     
     
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值