std::map .find().second
时间: 2024-06-18 17:03:16 浏览: 6
std::map是C++ STL中的一个关联式容器,它提供了一种映射的关系,可以将键值与数据值进行一一映射。其中,find()函数可以用来查找某个键值是否存在,如果存在,返回一个迭代器,否则返回末尾迭代器。而.second则是用来返回迭代器指向的元素的数据值(即映射关系中的值)。举个例子:
```
std::map<int, std::string> myMap;
myMap = "hello";
myMap = "world";
auto it = myMap.find(1);
if(it != myMap.end()) {
std::cout << it->second << std::endl; // 输出 hello
}
```
在上述代码中,我们定义了一个映射关系,将整数与字符串进行映射。然后使用find函数查找键值为1的元素是否存在,由于存在,所以返回了一个迭代器,通过迭代器的second成员函数获取到了与1对应的字符串"hello"。
相关问题
std::map.find()使用
在C++中,std::map是一个关联容器,它存储了一对键值对,并根据键的顺序进行排序。std::map.find()函数用于在map中查找指定的键,并返回一个指向该键的迭代器。如果找到了该键,则返回指向该键的迭代器;如果未找到,则返回指向map末尾的迭代器。
下面是std::map.find()的使用示例:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> mapS;
mapS[1] = "one";
mapS[2] = "two";
mapS[3] = "three";
std::map<int, std::string>::iterator it = mapS.find(2);
if (it != mapS.end()) {
std::cout << "Key found! Value: " << it->second << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
```
输出结果为:
```
Key found! Value: two
```
std::map::find
`std::map::find`是C++标准库中`std::map`容器提供的成员函数之一,用于在`std::map`中查找指定的键,并返回指向该键值对的迭代器。
以下是`std::map::find`函数的语法:
```cpp
iterator find (const key_type& key);
```
其中,`key_type`是`std::map`中键的数据类型。`key`是要查找的键。
以下是一个示例:
```cpp
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
std::map<int, std::string>::iterator it = myMap.find(2);
if (it != myMap.end()) {
std::cout << "Key found! Value: " << it->second << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
```
在上述示例中,我们创建了一个`std::map<int, std::string>`类型的`myMap`对象,并插入了几个键值对。然后,我们使用`find`函数查找键为2的元素,并将返回的迭代器赋值给`it`。如果找到了键为2的元素,则输出相应的值;如果没有找到,则输出"Key not found!"。
运行程序时,输出结果为:
```
Key found! Value: Two
```
这表示在`myMap`中成功找到了键为2的元素,并输出了对应的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)