title: Appending to a vector while iterating over it?
body: <p>I have a vector that I am iterating over.  While iterating, I may append new values to the vector.  It looks something like:</p>
  
  <pre><code>struct Foo
  {
     bool condition;
  };
  
  void AppendToVec(vector&lt;Foo&gt;&amp; v)
  {
     ...
     v.push_back(...);
  }
  
  vector&lt;Foo&gt; vec;
  ...
  for (vector&lt;Foo&gt;::size_type i = 0; i &lt; vec.size(); ++i)
  {
     if (vec[i].condition) AppendToVec(vec);
  }
  </code></pre>
  
  <p>This works fine, and in fact elegantly handles the case where the newly appended elements recursively require even more elements to be added, but it feels a little fragile.  If someone else comes along and tweaks the loop, it can easily be broken.  For example:</p>
  
  <pre><code>//No longer iterates over newly appended elements
  vector&lt;Foo&gt;::size_type size = vec.size();
  for (vector&lt;Foo&gt;::size_type i = 0; i &lt; size; ++i)
  {
     if (vec[i].condition) AppendToVec(vec);
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>//Vector resize may invalidate iterators
  for (vector&lt;Foo&gt;::iterator i = vec.begin(); i != vec.end(); ++i)
  {
     if (vec-&gt;condition) AppendToVec(vec);
  }
  </code></pre>
  
  <p>Are there any best practices to handle cases like this?  Is commenting the loop with a "Warning: This loop is intentionally appends to the vector while iterating.  Change cautiously" the best approach?  I am open to switching containers too if that makes things more robust.</p>