I have two std::map
maps and wish to merge them into a third map like this:
if the same key is found in both maps, create a pair in the third map wi
I don't think it will be easy (if not impossible) to find a suitable std::algorithm
that serves the purpose.
The easiest way would be to first make a copy of map1
to map_result
.
Then iterate through map2
and see if any key
already exists in map_result
then add the values
, else add the key_value
pair to map_result
.
std::map map_result( map1 );
for (auto it=map2.begin(); it!=map2.end(); ++it) {
if ( map_result[it->first] )
map_result[it->first] += it->second;
else
map_result[it->first] = it->second;
}