两个map合并成一个map,用insert()函数就可以了,看代码:
#include <map>
#include <iostream>
int main()
{
std::map<int, int> v1 = {{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}};
std::map<int, int> v2 = { {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}};
std::map<int, int> dest1 = v1;
dest1.insert(v2.begin(), v2.end());
for (const auto &i : dest1) {
std::cout << i.first << ':' << i.second << ' ';
}
std::cout << '
';
}
结果:
1:1 2:1 3:1 4:1 5:1 6:2 7:2
合并多个map,循环进行即可。
#include <map>
#include <iostream>
int main()
{
std::map<int, int> v1 = { {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1} };
std::map<int, int> v2 = { {4, 2}, {5, 2}, {6, 2}, {7, 2} };
std::map<int, int> v3 = { {8, 2}, {9, 2}};
std::map<uint32_t, std::map<int, int>> pp;
pp.insert({ 1,v1 });
pp.insert({ 2,v2 });
pp.insert({ 3,v3 });
std::map<int, int> dest1 ;
auto iter = pp.begin();
for (; iter != pp.end(); ++iter) {
dest1.insert(iter->second.begin(), iter->second.end());
}
for (const auto &i : dest1) {
std::cout << i.first << ':' << i.second << ' ';
}
std::cout << '
';
}
结果:
1:1 2:1 3:1 4:1 5:1 6:2 7:2 8:2 9:2
如果map中有重复的key,并且想保留多个相同key的键值对,则只需要,将目标map定义为std::multimap 。如下:
#include <map>
#include <iostream>
int main()
{
std::map<int, int> v1 = {{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}};
std::map<int, int> v2 = { {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}};
std::multimap<int, int> dest1 {v1.begin(), v1.end()};
dest1.insert(v2.begin(), v2.end());
for (const auto &i : dest1) {
std::cout << i.first << ':' << i.second << ' ';
}
std::cout << '
';
}
结果:
1:1 2:1 3:1 3:2 4:1 4:2 5:1 5:2 6:2 7:2
其他容器类似。