关联式容器 - map

另外在使用 map 时,要注意 [] 的一个使用技巧,来看一个例子:

#include <map>

// 单词 -> 出现次数的 map
std::map<std::string, size_t> words_map;

// 统计每个单词出现的次数
for (const auto &w : { "this", "is", "not", "a", "this", "is", "a"})
  ++words_map[w];

for (const auto &pair : words_map)
  std::cout << pair.first << ": " << pair.second << "times." << std::endl;

当一个单词不在 words_map 中时,++words_map[w] 就会将该单词插入,并将次数设置为 1,如果单词已经存在则不会再次插入,而仅仅将出现的次数(值)加 1,实现了统计单词出现次数的功能。

猜你喜欢

转载自my.oschina.net/itfanr/blog/1803148