Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two STL maps?

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

like image 385
JonF Avatar asked Sep 03 '10 21:09

JonF


People also ask

Can we add two maps in C++?

inserts each element from the range [i, j) if and only if there is no element with key equivalent to the key of that element in containers with unique keys; Since that std::map must follow this restriction, if you'd like to give preference to "values" from one map over another you should insert into it.

How can I compare two maps in C++?

C++ Map Library - operator== Functionb The C++ function std::map::operator== tests whether two maps are equal or not.


2 Answers

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(), mapB.end()) 

will do what you want, I think.

(EDIT: If you are using C++17 or newer, consider this answer: https://stackoverflow.com/a/56594603/118150)

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 
like image 133
jkerian Avatar answered Sep 22 '22 15:09

jkerian


If you want to copy entries from one map to another, you can use std::map's insert:

targetMap.insert(sourceMap.begin(), sourceMap.end()); 

But note that insert does not update elements if their key is already in targetMap; those items will be left as-is. To overwrite elements, you will have to copy explicitly, e.g.:

for(auto& it : sourceMap) {     targetMap[it.first] = it.second; } 

If you don't mind losing the data in sourceMap, another way to achieve a copy-and-overwrite is to insert the target into the source and std::swap the results:

sourceMap.insert(targetMap.begin(), targetMap.end()); std::swap(sourceMap, targetMap); 

After swapping, sourceMap will contain targetMap's old data, and targetMap will be a merge of the two maps, with preference for sourceMap's entries.

like image 38
kiwibonga Avatar answered Sep 22 '22 15:09

kiwibonga