遍历map如果没有存在的key值插入在map中
时间: 2023-05-23 18:04:57 浏览: 58
A:可以使用`map::insert()`函数插入新的键值对。当插入的键已经存在于map中时,该函数会返回一个`pair`类型的值,其中`pair.first`指向已经存在的键的位置,`pair.second`为`false`;当插入的键不存在于map中时,该函数会插入该键值对并返回一个`pair`类型的值,其中`pair.first`指向插入后的键的位置,`pair.second`为`true`。
示例代码:
```c++
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> myMap;
myMap.insert(std::make_pair("apple", 1));
myMap.insert(std::make_pair("banana", 2));
myMap.insert(std::make_pair("orange", 3));
std::map<std::string, int>::iterator it;
std::pair<std::map<std::string, int>::iterator, bool> ret;
// 插入键为"kiwi",值为4
ret = myMap.insert(std::make_pair("kiwi", 4));
if (ret.second == false) {
std::cout << "kiwi already exists in the map" << std::endl;
}
// 插入键为"orange",值为5
ret = myMap.insert(std::make_pair("orange", 5));
if (ret.second == false) {
std::cout << "orange already exists in the map" << std::endl;
std::cout << "the value of orange in the map is: " << ret.first->second << std::endl;
}
// 遍历map
for (it = myMap.begin(); it != myMap.end(); it++) {
std::cout << it->first << " => " << it->second << std::endl;
}
return 0;
}
```