How can I append the content of one map to another map?

Cute picture Cute · Jul 1, 2009 · Viewed 28.3k times · Source

I have the following two maps:

map< string, list < string > > map1;
map< string, list < string > > map2;

I populated map1 with the following content:

1. kiran; c:\pf\kiran.mdf, c:\pf\kiran.ldf
2. test;  c:\pf\test.mdf, c:\pf\test.mdf

Then I copied the content of map1 into map2 as follows:

map2 = map1;

Then I filled map1 again with the following new content:

1. temp; c:\pf\test.mdf, c:\pf\test.ldf
2. model; c:\model\model.mdf, c:\pf\model.ldf

Now I have to append this content to map2. I cannot use map2 = map1;, because this will overwrite the existing content in map2. So, how can I do this?

Answer

Nick Lewis picture Nick Lewis · Jul 14, 2009
map<int,int> map1;
map<int,int> map2;
map1.insert(map2.begin(), map2.end());

This will insert into map1 the elements from the beginning to the end of map2. This method is standard to all STL data structure, so you could even do something like

map<int,int> map1;
vector<pair<int,int>> vector1;
vector1.insert(map1.begin(), map1.end());

Furthermore, pointers can also function as iterators!

char str1[] = "Hello world";
string str2;
str2.insert(str1, str1+strlen(str1));

Highly recommend studying the magic of the STL and iterators!