c++ - 何时检查项目是否已存在于 C++ 集合/映射中?

标签 c++ dictionary set unordered-map unordered-set

我有一个关于 C++ STL 中的 set、unordered_set、map、unordered_map 的一般性问题。

我经常看到代码在尝试更改其值之前检查某个项目是否已经在集合/映射中。

我想知道,什么时候在尝试修改某个项目之前手动检查它是否已经存在于集合/ map 中是明智的?

例如:

unordered_set<string> banwords(banned.begin(), banned.end());
unordered_map<string, int> count;
string word = "test";

if (banwords.find(word) == banwords.end()){

    ++count[word];
    if (count[word] > maxpair.second){
        maxpair.first = word;
        maxpair.second = count[word];
    }
}

不进行检查以确定单词是否已存在于计数中,而是假定 count[word] = 0 甚至在它存在于 map 中之前。

另一方面,我看到其他线程鼓励先检查该项目是否存在。

这里推荐的解决方案是什么?

最佳答案

这里的关键是当 word 不在 map 中时,count[word] 在 map 中创建一个新条目,键为 word 和 0 的值。所以 ++count[word] 总是有效的;无需检查。

关于c++ - 何时检查项目是否已存在于 C++ 集合/映射中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55778030/

相关文章:

java - 如何检查HashSet中是否已经存在对象?

c++ - 结构运算符函数重载中的偶发段错误

c++ - 为什么我们不能用右值 volatile int&& 初始化对 const int 的引用?

c++ - 尝试设置一个数组以将最后三笔存款存储到银行账户系统中

c# - 将双 for 循环转换为 linq 查询

python - 使用正则表达式查询集合

c++ - 如何在 C++ 中使用 AB 剪枝遍历数字网格?

c# - 为什么 IDictionary<TKey,TValue> 不/不能实现 ILookup<TKey,TValue>?

list - python : Sending a dictionary's items to a list of lists

Haskell 合格导入(创建空集)