Here is an example of how to complete a task using std :: accumulate
#include <iostream> #include <map> #include <numeric> int main() { std::map<int, int> m1 = { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }; std::map<int, int> m2 = { { 2, 5 }, { 3, 1 }, { 5, 5 } }; for ( const auto &p : m1 ) { std::cout << "{ " << p.first << ", " << p.second << " } "; } std::cout << std::endl; for ( const auto &p : m2 ) { std::cout << "{ " << p.first << ", " << p.second << " } "; } std::cout << std::endl; std::map<int, int> m3 = std::accumulate( m1.begin(), m1.end(), std::map<int, int>(), []( std::map<int, int> &m, const std::pair<const int, int> &p ) { return ( m[p.first] +=p.second, m ); } ); m3 = std::accumulate( m2.begin(), m2.end(), m3, []( std::map<int, int> &m, const std::pair<const int, int> &p ) { return ( m[p.first] +=p.second, m ); } ); for ( const auto &p : m3 ) { std::cout << "{ " << p.first << ", " << p.second << " } "; } std::cout << std::endl; return 0; }
Output signal
{ 1, 1 } { 2, 2 } { 3, 3 } { 4, 4 } { 2, 5 } { 3, 1 } { 5, 5 } { 1, 1 } { 2, 7 } { 3, 4 } { 4, 4 } { 5, 5 }
In fact, only for the second card you need to use std :: accumulate. The first card can simply be copied or assigned to m3.
for instance
std::map<int, int> m3 = m1; m3 = std::accumulate( m2.begin(), m2.end(), m3, []( std::map<int, int> &m, const std::pair<const int, int> &p ) { return ( m[p.first] +=p.second, m ); } );