C++中的迭代器和常量交互器

Sup*_*ing 0 c++ iterator

有什么不同?

我希望能够看到一个元素是否在HashMap中,我发现如果我执行h [element],它将返回默认元素(如果找不到),而不是null.我如何使用迭代器查找方法来查看元素是否存在?

谢谢

Nic*_*lás 6

假设您正在谈论STL而不是某些第三方库... m[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
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不需要获取对象(您只想知道它是否存在):

map<string, int> mymap;
//add items to it
if (mymap.count("key") == 1) {
    // 'key' exists
}
Run Code Online (Sandbox Code Playgroud)