我有一个关于 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/