Since C++17 std::map
provides a merge()
member function, so you can simply call map1.merge(map2);
. Please note, that a map is sorted by its keys, so that elements will not necessarily be appended at the end. Also, because the keys in a map are unique, not all elements from map2
might be inserted into map1
. Full example:
int main() {
std::map<std::string, std::map<std::string, std::string>> map1{
{"a", {{"b", "b"}}}, {"b", {{"c", "c"}}}
};
std::map<std::string, std::map<std::string, std::string>> map2{
{"b", {{"x", "x"}}}, {"c", {{"y", "y"}}}
};
map1.merge(map2); // C++17
std::cout << "map1:" << std::endl;
for (auto const &kv : map1)
std::cout << kv.first << ": " << kv.second.begin()->first << std::endl;
std::cout << std::endl << "map2:" << std::endl;
for (auto const &kv : map2)
std::cout << kv.first << ": " << kv.second.begin()->first << std::endl;
return 0;
}
Output:
map1:
a: b
b: c
c: y
map2:
b: x
As you can see, merge()
does not overwrite existing elements in the target map map1
when keys overlap. If you want to to give priority to elements from map2
, then you have to call map2.merge(map1);
. As you can also see, merge()
moves entries over from the source map. Elements that cannot be merged remain in map2
.
Code on Coliru