1

I would like to ask how can I iterate over map of maps. I do have this map - std::map <string, std::map <string, double> > myMap and I would like to iterate through it like in a 2D array. I am little bit familiar with the iterators, but I haven't iterated through a 2D map before.

I do currently have one for cycle with my iterator, but I have no idea how to iterate over the second map. Can you give me some hints ?

Thank you for your answers

Jesse_Pinkman
  • 565
  • 1
  • 8
  • 21

1 Answers1

3

This prints a key in the outer map followed by each string/double entry in the inner map for the outer map key - and then does the same for the next key in the outer map.

for(auto & outer_map_pair : myMap) {
  cout << outer_map_pair.first << " contains: " << endl;
  for(auto & inner_map_pair : outer_map_pair.second) {
    cout << inner_map_pair.first << ": " << inner_map_pair.second << endl;
  }
}

This might print:

foo contains:
bar: 4.4
baz: 5.5
stuff contains:
a: 1.1
b: 2.2
c: 3.3
xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • thank you for your answer, but compiler keeps telling me "inner_map was not declared" - didn't you mean outer_map_pair.second or something like that in the second for cycle ? – Jesse_Pinkman Mar 13 '16 at 11:28
  • updated answer. I changed a variable name in one place but not another. – xaxxon Mar 13 '16 at 11:38