I have a code with nested traversals involving STL containers. In particular I have a top container ( a list) which contains sublists and those sublists contain further sublists. For e.g. In a DICOM structure, a patient can have multiple Studies and each Study can have multiple Series. I have to perform some operation on Series objects and the only way to reach them is to drill down deep in a loop as shown below.
The pseudocode looks like this.
STLContainer top;
STLContainer::iterator top_iter;
for ( top_iter= top.begin(); top_iter != top.end(); ++top_iter) {
STLContainer mid = *top_iter;
STLContainer::iterator mid_iter;
for ( mid_iter = mid.begin(); mid_iter!= mid.end(); ++mid_iter) {
STLContainer bottom = *mid_iter;
STLContainer::iterator bottom_iter;
for(bottom_iter = bottom.begin(); bottom_iter != bottom.end(); ++bottom_iter){
ExecuteSomething(*bottom_iter); // Finally do something with the stored object
}
}
}
Now If I have to execute a series on operations repeatedly on these 'bottom' objects, I have to do this traversal again and again. If i wish to use STL Algorithms, I would need to write atleast 3 lines of "for_each" for each level of nesting.
Does anyone know of a technique to shorten this code which can work a bit like this?
// Drills down to the deepest nested container
for_each(top.begin(), top.end(), DrillDownAndExecuteOnBottom());
which can work in just one single line? Something like this? Thanks!