map容器

对于map容器,如果下标所表示的键在容器中不存在,则添加新元素,这一特性可以使程序惊人地简练:

//count number of times each word occurs in the input
map<string, int> word_count;   //empty map from string to int
while(cin>>word)
    ++word_count[word];

这段程序创建一个map对象,用来记录每个单词出现的次数。


使用insert重写的单词统计程序:

// count number of times each word occurs in the input
map<string, int> word_count;   //empty map from string to int
string word;
while(cin>>word){
     // inserts element with key equal to word and value ;
     // if word already in word_count, insert does nothing
     pair<map<string, int>::iterator, bool> ret =
            word_count.insert(make_pair(word,1));
     if (!ret.second)         // word already in word_count
         ++ret.first->second;   // increment counter
}

第一段程序是使用下标操作符来在map中插入,第二段程序使用insert来插入。使用insert的好处是可以避免下标操作符带来的”初始化“的副作用。因为在下标操作过程中,值先进行初始化,然后再赋值。


来自 C++ Primer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值