title: Qt: is removing QList elements while iterating using foreach macro possible?
body: <p>I'm new to Qt and trying to learn the idioms.</p>
  
  <p>The <a href="https://doc.qt.io/qt-5/containers.html#the-foreach-keyword" rel="nofollow noreferrer"><code>foreach</code> documentation</a> says:</p>
  
  <blockquote>
    <p>Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop.</p>
  </blockquote>
  
  <p>But it doesn't say <em>how</em> to remove an element while iterating with <code>foreach</code>.  My best guess is something like:</p>
  
  <pre><code>int idx = 0;
  foreach (const Foo &amp;foo, fooList) {
    if (bad(foo)) {
      fooList.removeAt(idx);
    }
    ++idx;
  }
  </code></pre>
  
  <p>Seems ugly to have to scope <code>idx</code> outside the loop (and to have to maintain a separate loop counter at all).</p>
  
  <p><s>Also, I know that <code>foreach</code> makes a copy of the <code>QList</code>, which is cheap, but what happens once I remove an element -- is that still cheap or is there an expensive copy-on-modify going on?</s> Yes, <a href="https://stackoverflow.com/questions/6866183/when-does-a-deep-copy-happen-to-a-qlist">deep copy happens</a>.</p>
  
  <p><strong>EDIT :</strong> This doesn't seem like idiomatic Qt either.</p>
  
  <pre><code>for (int idx = 0; idx &lt; fooList.size(); ) {
    const Foo &amp;foo = fooList[idx];
    if (bad(foo)) {
      fooList.removeAt(idx);
    }
    else ++idx;
  }
  </code></pre>