MistyD
MistyD

Reputation: 17223

Merge two maps <string,int>

Suppose I have two maps

std::map<string,int> mapA;

mapA["cat"] = 1;
mapA["dog"] = 3;

then the other map is mapB

std::map<string,int> mapB;

mapB["cat"] = 1;
mapB["horse"] = 3;

Now I need to merge mapB into mapA so the final mapA looks like this after merge

mapA["cat"] = 2;
mapA["dog"] = 3;
mapA["horse"] = 3;

I wanted to know what would the best way be to achieve this ? I know that i could iterate through MapB and check if each element is in MapA if it is then increment the value otherwise Add it to MapA. My question is if there is an algorithm or a faster more efficient approach ?

Upvotes: 0

Views: 80

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

template <class M>
void add_maps(M const& source, M& dest)
{
    for (auto const& entry : source)
        dest[entry.first] += entry.second;
}

Upvotes: 4

Related Questions