存入map对象
时间: 2023-07-03 09:27:21 浏览: 47
好的,我可以为您提供一些存储数据到 map 对象的示例代码。请注意,您需要使用 map 的 insert() 函数或 [] 运算符来插入键值对。下面是一个简单的示例:
```c++
#include <iostream>
#include <map>
#include <string>
int main() {
// 创建一个字符串到整数的 map 对象
std::map<std::string, int> my_map;
// 使用 insert() 函数插入键值对
my_map.insert(std::pair<std::string, int>("apple", 1));
my_map.insert(std::pair<std::string, int>("banana", 2));
my_map.insert(std::pair<std::string, int>("cherry", 3));
// 使用 [] 运算符插入键值对
my_map["orange"] = 4;
my_map["kiwi"] = 5;
// 遍历 map 对象并输出键值对
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
在上面的示例中,我们创建了一个字符串到整数的 map 对象,并使用 insert() 函数和 [] 运算符分别插入了一些键值对。然后,我们使用迭代器遍历 map 对象并输出键值对。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)