当 wordCount 中不存在键时,我应该为 unordered_map<string, int> 使用 ++wordCount[key] 吗?

should I use ++wordCount[key] for unordered_map<string, int> when key doesn't exist in wordCount?

查看下面的代码:

unordered_map<string, int> wordCount;
for(string word: words)
    ++wordCount[word];

问题:

当 wordCount 中不存在单词时使用 ++wordCount[word]; 是否就在这里?总看到有人这样用,但我不是很确定。

解释 here 说:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

我知道 int is uninitialized in default。所以,我觉得这样直接增加地图值是不安全的,是吗?

operator[]

上引用 cppreference 的文档

When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.

关键词是value-initialized。值初始化的 int 为零。

这是 official reference(C++14,23.5.4.3 第 2 段,[unord.map.elem]):

Effects: If the unordered_map does not already contain an element whose key is equivalent to k, the first operator inserts the value value_type(k, mapped_type()) and the second operator inserts the value value_type(std::move(k), mapped_type()).

注意 mapped_type(),对于 mapped_type = int 将构造一个零值 int