如何向map容器中添加元素
时间: 2024-03-26 22:39:30 浏览: 13
向 map 容器中添加元素的方法是使用 insert() 函数,具体来说,可以使用以下几种方式:
1. 使用 std::pair 对象添加元素:
```c++
std::map<std::string, int> myMap;
myMap.insert(std::pair<std::string, int>("apple", 1));
myMap.insert(std::pair<std::string, int>("banana", 2));
```
2. 使用 value_type 对象添加元素:
```c++
std::map<std::string, int> myMap;
myMap.insert(std::map<std::string, int>::value_type("apple", 1));
myMap.insert(std::map<std::string, int>::value_type("banana", 2));
```
3. 使用 initializer_list 添加元素:
```c++
std::map<std::string, int> myMap{{"apple", 1}, {"banana", 2}};
```
注意,如果 key 已经存在于 map 中,insert() 操作将不会添加元素。此时可以使用 [] 运算符来更新 key 对应的 value。例如:
```c++
std::map<std::string, int> myMap;
myMap["apple"] = 1; // 使用 [] 运算符添加元素
myMap["banana"] = 2;
```