title: How to efficiently replace elements in an unordered_set while iterating over it?
body: <p>Suppose you have an</p>
  
  <pre><code>std::unordered_set&lt;std::shared_ptr&lt;A&gt;&gt; as;
  // (there is an std::hash&lt;std::shared_ptr&lt;A&gt;&gt; specialisation)
  </code></pre>
  
  <p>and you want to replace some of its elements while iterating over it:</p>
  
  <pre><code>for (auto it = as.begin(); it != as.end(); ++it) {
    if ((*it)-&gt;condition()) {
      as.erase(it);
      as.insert(std::make_shared&lt;A&gt;(**it));
    }
  }
  </code></pre>
  
  <p>This could <strong>invalidate</strong> the iterator at <code>erase</code> and <code>insert</code> (if rehashing takes place), so this loop will exhibit undefined behaviour and will most likely crash horribly.</p>
  
  <p>The one solution I can think of is using two separate <code>vector</code>s to buffer the <code>insert</code> and <code>erase</code> operations and later use the overloads that take iterator pairs for erasing and inserting (this is presumably more rehashing-friendly).</p>
  
  <p>Even if I use the buffer approach, this still seems bloated code and could result in two rehashes that might possibly both be unnecessary.</p>
  
  <p>So, is there a better way to do it?</p>