I m not too sure what the question is: the title speaks of "maps of
maps", but I don t see any in the example code.
Other than that: what should occur if an item was deleted by the
function? Do you want to restart the iteration from the start, or
continue where you left off (knowing that where you left off might have
been removed from the map)? For the first, your code is basically
correct, and I don t think that there s a better solution; at least I
can t think of one off hand. For the second, I think you d want
something like:
iter = map.begin();
while ( iter != map.end() ) {
key = iter->first;
// call function...
iter = map.upper_bound( key );
}
This is probably the simplest solution. map.upper_bound
is O(lg n)
,
however; if the map is large, this could be a problem. Depending on the
implementation of map
(and the frequency with which your function
removes elements), using ++
on the iterator if nothing has been
removed from the map might be faster.
Of course, if you can guarantee that the function in question never
deletes the element after the one you re at, you can increment the
iterator before calling the function. The solution with upper_bound
,
however, works unconditionally, regardless of what the function changes
in the map.