c++ - C++中的迭代器和常量迭代器

标签 c++ iterator

有什么区别?

我希望能够查看一个元素是否在 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/

相关文章:

c++ - 将参数传递给 C++ CORBA 方法实现

c++ - 无法从 SQLite3 表中删除记录

c++ - 临时对象的生命周期 : iterator to temporary vector in nested function call

c++ - 传递函数作为参数

c++ - IntelMPI 错误(适用于 openMPI)

java - 以速度迭代字符串

c++ - 删除二维 vector 行中的元素 - 使用迭代器

c++ - 使用反向迭代器在 C++ 中反转字符串?

iterator - 如何为简单结构实现 Iterator 和 IntoIterator?

c++ - 如何删除和删除指向存储在 vector 中的对象的指针?