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

后端 未结 3 1619
遇见更好的自我
遇见更好的自我 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 23:00

    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;
    }
    

提交回复
热议问题