tags:

views:

151

answers:

6

Hello,

Anybody knows how to concat these two map:

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

I just want to add map2 to map1 and keep all elements already in map1 i.e. add map2 at the end of map1. I'v tried map1.insert(map2.begin(), map2.end()) but it does not work since it overwrites old elements in map1.

thx, /Niklas

A: 

something went wrong when I wrote earlier. The two map are of type: map(string,map(string,string))

Niklas
use code for the map declaration, otherwise we cannot possibly understand your code because "\<" is interpretted in html.
Iulian Şerbănoiu
You can edit your question to fix it :)
psmears
In the mean time, I edited it. You can use backquotes to surround `inline code`.
xtofl
+4  A: 

map<> can contain only one value for one key. try using multimap<>, for example.

Yossarian
+1  A: 

The question contradicts with the concept of a map. If you insert a value in a map, you expect it to be at 'the proper place', depending on it's key. This implies there is only one entry for each key.

Instead, you could use a vector< pair< mymap::key, myamap::value > > and fill it with the entries of the first resp. the second map.

map< string, int > map1, map2;
... fill the maps
vector< pair<string, int> > concatted;
concatted.insert( map1.begin(), map1.end() );
concatted.insert( map2.begin(), map2.end() );
xtofl
But doesn't this create two different map i.e. a list containing map[0], map[1]... All I want to do is append maps to another map in a for loop.
Niklas
@Niklas: that's the point: you cannot append two maps. You can create the 'union', but double entries will get lost.
xtofl
+1  A: 

Do it with a simple for-loop: (althrough i like to use stl algorithms where plausible):

for(std::map<...>::const_iterator it = map2.begin(), it_end = map2.end(); it != it_end; ++it)
   map1.insert(*it);

Any element whose key already is in map1 won't be overwritten as map::insert doesn't overwrite.

Viktor Sehr
so it conceptually 'overwrites' the entries in `map2`. Back at sqr 1?
xtofl
Que? It does not modify map2 in any way.
Viktor Sehr
+1  A: 

If a map is not too big, do the opposite:

map2.insert(map1.begin(), map1.end());
map1 = map2;

This will overwrite duplicate values in map2, but will keep the ones in map1 (I understand this is what you wanted).

Alex B
Actually, why does insert with a range replaces and insert with one element doesn't?
KillianDS
+3  A: 

If you just want to merge them but in case of collisions keep the elements from map1, then just reverse the maps:

std::swap(map1, map2);
map1.insert(map2.begin(), map2.end());

This of course assumes that after the merge, you're only interested in the result and lo longer in the old collections.

MSalters
+1 this is what my answer should have been.
Alex B