title: Generalising multiple nested for loops
body: <p>I have a data structure like this: <code>map&lt;string, map&lt;string, map&lt;string, MyObj&gt;&gt;&gt;</code></p>
  
  <p>Now, I have multiple functions all of which use the same for loop method:</p>
  
  <pre><code>for (auto p1 : myMap)
      for (auto p2 : p1.second)
          for (auto p3 : p2.second)
              doThingsWith(p1, p2, 3);
  </code></pre>
  
  <p>Where the <code>doThingsWith(p1, p2, p3)</code> varies between functions, as well as the code before and after the for loops. Also, some functions only need to access <code>MyObj</code> objects for example, while others need access to all the string keys as well as the <code>MyObj</code> objects.</p>
  
  <p>So, the question is, is there any method to generalise this without losing performance? I came up with a function that returns a vector of tuples:</p>
  
  <pre><code>vector&lt;tuple&lt;string, string, string, MyObj&gt;&gt; getData(... &amp;myMap)
  {
      vector&lt;tuple&lt;string, string, string, MyObj&gt;&gt; data;
      for (auto p1 : myMap)
          for (auto p2 : p1.second)
              for (auto p3 : p2.second)
                  data.push_back(tuple&lt;string, string, string, MyObj&gt;(
                      p1.first, p2.first, p3.first, p3.second
                  ));
      return data;
  }
  </code></pre>
  
  <p>And now my functions can use this:</p>
  
  <pre><code>for (auto t : getData(myMap))
      doThingsWith(get&lt;0&gt;(t), get&lt;1&gt;(t), get&lt;2&gt;(t), get&lt;3&gt;(t));
  </code></pre>
  
  <p>But this is unnecessarily constructs <em>a lot of</em> tuples and vectors, since <code>myMap</code> is huge.</p>
  
  <p>Is there any better way? In Python I can use generators, but I don't know the C++ equilevant:</p>
  
  <pre><code>def iterTuples(myMap):
      for k1, v1 in myMap.items():
          for k2, v2 in v1.items():
              for k3, v3 in v2.items():
                  yield k1, k2, k3, v3
  
  
  for k1, k2, k3, val in iterTuples(myMap):
      doThingsWith(k1, k2, k3, val)
  </code></pre>