tags:

views:

93

answers:

1
+2  Q: 

Merge STL map's

How can I merge two STL maps into one? They both have the same key value types (map). If there is overlap of the keys I would like to give preference to one of the maps.

+7  A: 

Assuming you want to preserve the elements in mapA, and merge elements in mapB for which there is no key in mapA:

mapA.insert(mapB.begin(), mabB.end())

will do what you want, I think.

EDIT: adding working example

#include <iostream>
#include <map>

void printIt(std::map<int,int> m) {
    for(std::map<int,int>::iterator it=m.begin();it!=m.end();++it)
        std::cout << it->first<<":"<<it->second<<" ";
    std::cout << "\n";
}

int main() {
    std::map<int,int> foo,bar;
    foo[1] = 11; foo[2] = 12; foo[3] = 13;
    bar[2] = 20; bar[3] = 30; bar[4] = 40;
    printIt(foo);
    printIt(bar);
    foo.insert(bar.begin(),bar.end());
    printIt(foo);
    return 0;
}

output:

:!./insert
1:11 2:12 3:13
2:20 3:30 4:40
1:11 2:12 3:13 4:40
jkerian
I can't see how that doesn't override a duplicate in mapA if the keys match. If I just say that mapB was my "preferred" map I could use this I think. That way if it's a duplicate then it the key in mapB would be the one that ultimately ends on in the new map (which is now mapA). Does that sound correct or am I misunderstanding what insert does when there is a duplicatE?
JonF
Insert will not overwrite existing elements, when there is a clash in the keys, the already existing element takes precedence.
David Rodríguez - dribeas
oh i see. unfortunetly it doesn't build though. It generates a huge error message
JonF
Sample code added, the basic concept is sound. What sort of error? (Ideally on a simplified code path)
jkerian