我有一個涉及STL容器的嵌套遍歷的代碼。特別是我有一個包含子列表的頂級容器(一個列表),這些子列表包含更多的子列表。對於例如在DICOM結構中,患者可以進行多項研究,每項研究可以有多個系列。我必須對Series對象執行一些操作,並且唯一的方法是深入到下面的循環中。簡化嵌套的STL容器遍歷
僞代碼看起來像這樣。
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
}
}
}
現在,如果我要重複執行這些「底部」對象上操作的系列,我不得不一次又一次地這樣做遍歷。如果我希望使用STL算法,那麼我需要爲每個嵌套級別寫入至少3行「for_each」。
有沒有人知道縮短這個代碼的技巧,可以這樣工作?
// Drills down to the deepest nested container
for_each(top.begin(), top.end(), DrillDownAndExecuteOnBottom());
哪個可以在一條線上工作?像這樣? 謝謝!
曾經有一個_Boost proposed_ iterator,展現了嵌套容器。 –
你可以製作一個對單個對象和容器(甚至是單個對象,單個元素容器和映射類型容器)都適用的通用'iterate'模板,它對單個元素執行實際操作,但是對容器進行迭代。 –