【发布时间】:2019-04-20 21:46:05
【问题描述】:
我有一个关于 C++ STL 中的 set、unordered_set、map、unordered_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 甚至在它甚至存在于地图中之前。
另一方面,我看到其他线程鼓励先检查项目是否存在。
这里有什么推荐的解决方案?
【问题讨论】:
标签: c++ dictionary set unordered-map unordered-set