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

后端 未结 3 1666
遇见更好的自我
遇见更好的自我 2021-02-07 22:20

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

3条回答
  •  花落未央
    2021-02-07 22:40

    Here is an example how to do the task with using std::accumulate

    #include 
    #include 
    #include 
    
    int main() 
    {
        std::map m1 = { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }; 
        std::map 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 m3 = std::accumulate( m1.begin(), m1.end(), std::map(),
            []( std::map &m, const std::pair &p )
            {
                return ( m[p.first] +=p.second, m );
            } );
    
        m3 = std::accumulate( m2.begin(), m2.end(), m3,
            []( std::map &m, const std::pair &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 m3 = m1;
        m3 = std::accumulate( m2.begin(), m2.end(), m3,
            []( std::map &m, const std::pair &p )
            {
                return ( m[p.first] +=p.second, m );
            } );
    

提交回复
热议问题