gpt4 book ai didi

c++ - 当 wordCount 中不存在键时,我应该对 unordered_map 使用++wordCount[key] 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:24 28 4
gpt4 key购买 nike

见下面的代码:

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

问题:

当wordCount 中不存在word 时,是否可以使用++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 .所以,我觉得这样直接增加 map 值是不安全的,对吧?

最佳答案

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 .

关于c++ - 当 wordCount 中不存在键时,我应该对 unordered_map<string, int> 使用++wordCount[key] 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323096/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com