C++的map插入数据
时间: 2023-07-27 15:07:28 浏览: 49
在C++中,可以使用STL库中的`map`来存储键值对数据,插入数据的方式有以下两种:
1. 使用`insert()`函数插入数据
```c++
#include <map>
#include <iostream>
int main() {
// 定义一个map
std::map<int, std::string> my_map;
// 插入数据
my_map.insert(std::pair<int, std::string>(1, "apple"));
my_map.insert(std::pair<int, std::string>(2, "banana"));
my_map.insert(std::pair<int, std::string>(3, "orange"));
// 遍历map
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
2. 使用`[]`运算符插入数据
```c++
#include <map>
#include <iostream>
int main() {
// 定义一个map
std::map<int, std::string> my_map;
// 插入数据
my_map[1] = "apple";
my_map[2] = "banana";
my_map[3] = "orange";
// 遍历map
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
```
两种方式都可以插入数据,但是使用`insert()`函数可以避免重复插入,而使用`[]`运算符则会覆盖原有的值。