将map<string> map1和map<string> map2合并为map<string,string> map3
时间: 2023-12-08 22:06:26 浏览: 65
一位map,二位map变成字符串后,再变成map的解析过程
可以使用迭代器遍历map1和map2,将它们的键值对存入map3中。代码示例如下:
```cpp
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, string> map3;
map<string, string> map1 = {{"key1", "value1"}, {"key2", "value2"}};
map<string, string> map2 = {{"key3", "value3"}, {"key4", "value4"}};
// 将map1中的键值对存入map3中
for (auto it = map1.begin(); it != map1.end(); ++it) {
map3[it->first] = it->second;
}
// 将map2中的键值对存入map3中
for (auto it = map2.begin(); it != map2.end(); ++it) {
map3[it->first] = it->second;
}
// 遍历输出map3中的键值对
for (auto it = map3.begin(); it != map3.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
输出结果为:
```
key1: value1
key2: value2
key3: value3
key4: value4
```
阅读全文