title: Iterating over a tree while removing and reinserting an element
body: <p>Take a look at this code excerpt:</p>
  
  <pre><code>while( *it &lt;= *it_end and it != myset.end() )
      if(foo(*it++))
          return true;
  </code></pre>
  
  <p><code>it</code> and <code>it_end</code> are valid iterators of std::set (an RB tree).</p>
  
  <p><code>foo</code> will either:</p>
  
  <ul>
  <li>Remove <code>it</code>, and insert again an element with the same value of <code>*it</code>, returing false;</li>
  <li>Remove <code>it</code> and return true.</li>
  </ul>
  
  <p>My question:</p>
  
  <p>Is it safe to run this loop? </p>
  
  <p>Before calling <code>foo</code>, <code>it</code> will be a valid iterator to the next element of the tree, however I'm afraid that some inner magic inside std::set makes that iterator invalid, like the self-balancing algorithms of the RB tree.</p>