有什么区别?
我希望能够查看一个元素是否在 HashMap 中,我刚刚发现如果我执行 h[element],如果没有找到它,它将返回默认元素,而不是 null。如何使用迭代器查找方法查看元素是否存在?
谢谢
最佳答案
假设您谈论的是 STL 而不是某些第 3 方库...m[key]
不仅会在 key 不在映射中时返回默认对象。它将使用该键和默认构造的对象作为值在映射中创建一个新元素。
你可以使用这个:
map<string, int> mymap;
//add items to it
map<string, int>::iterator it = mymap.find("key");
if (it != myMap.end()) {
// 'key' exists; (it->second) is the corresponding int
}
或者如果你不需要获取对象(你只想知道它是否存在):
map<string, int> mymap;
//add items to it
if (mymap.count("key") == 1) {
// 'key' exists
}
关于c++ - C++中的迭代器和常量迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1954249/