Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two maps, summing values for same keys in C++

Tags:

c++

merge

maps

I have two std::map<int,int> 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 with the same key and a value which a sum of values from the first and second map, otherwise just copy a pair to the third map. I suspect it can be done with std::accumulate, but I don't understand it well enough.

like image 286
Chiffa Avatar asked Dec 25 '13 10:12

Chiffa


1 Answers

Here is an example how to do the task with 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;
}

The output is

{ 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 map there is a need to use std::accumulate. The first map can be simply copied or assigned to m3.

For example

    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 );
        } );
like image 98
Vlad from Moscow Avatar answered Oct 23 '22 04:10

Vlad from Moscow