C++98: 合并两个 std::map - 详细示例与代码
在 C++98 标准中,可以使用循环遍历源 map 的每个键值对,然后将其插入到目标 map 中。以下是一个示例代码:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> src;
src['key1'] = 1;
src['key2'] = 2;
std::map<std::string, int> dest;
dest['key3'] = 3;
dest['key4'] = 4;
std::map<std::string, int>::iterator it;
for (it = src.begin(); it != src.end(); ++it) {
dest.insert(std::make_pair(it->first, it->second));
}
// 输出合并后的 map
for (it = dest.begin(); it != dest.end(); ++it) {
std::cout << it->first << ' => ' << it->second << std::endl;
}
return 0;
}
上述代码中,我们先创建了两个 map,src 和 dest,src 是要合并到 dest 中的 map。然后,我们使用迭代器遍历 src,并使用 insert 函数将每个键值对插入到 dest 中。
最后,我们使用循环遍历 dest,并打印出所有的键值对,以验证合并结果。
输出结果为:
key1 => 1
key2 => 2
key3 => 3
key4 => 4
原文地址: https://www.cveoy.top/t/topic/gTxK 著作权归作者所有。请勿转载和采集!