c++ map.find->second
时间: 2024-05-17 22:18:48 浏览: 363
对于C++中的std::map容器,使用map.find()方法可以查找特定的键,并返回一个迭代器,指向该键对应的键值对。要访问这个键值对的值,可以使用迭代器的second成员。示例代码如下:
```cpp
std::map<int, std::string> myMap;
myMap[1] = "Hello";
myMap[2] = "World";
auto iter = myMap.find(1);
if (iter != myMap.end()) {
std::cout << iter->second << std::endl; // 输出 "Hello"
} else {
std::cout << "Key not found" << std::endl;
}
```
在这个例子中,我们创建了一个std::map对象myMap,并插入了两个键值对。然后使用find(1)方法查找键为1的键值对,并将返回的迭代器赋值给iter。通过访问iter->second,我们可以获取到键为1的值 "Hello" 并输出它。
请注意,如果查找的键不存在于map中,find()方法将返回map.end(),表示未找到。因此,在访问迭代器之前,应始终检查迭代器是否等于map.end(),以避免访问不存在的键值对导致的错误。
阅读全文
相关推荐









