对于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