title: How do we iterate through all elements of a set while inserting new elements to it?
body: <p>consider this:</p>
  
  <pre><code>// set_iterator.cpp : Defines the entry point for the console application.
  
  #include "stdafx.h"
  #include &lt;iostream&gt;
  #include &lt;set&gt;
  
  using namespace std;
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      set&lt;int&gt; a1;
      set&lt;int&gt; a2;
  
      a1.insert(3);
      a1.insert(4);
      a1.insert(5);
      a2.insert(1);
      a2.insert(2);
      a2.insert(6);
  
      set&lt;int&gt;::iterator iter;
      int x = 0;
      for (iter = a1.begin(); iter != a1.end(); ++iter)
      {
          if (x == 0) {
              x = 1;
              a1.insert(a2.begin(), a2.end());
          }
          cout &lt;&lt; *iter &lt;&lt; endl;
      }
  
      system("pause");
  
      return 0;
  }
  </code></pre>
  
  <p>goal is to visit each element of the set exactly once. i think the iterator is not valid after we insert elements into a1.</p>
  
  <p>output is
  3 4 5 6</p>
  
  <p>1,2 are not printed.</p>
  
  <p>how do we code such a situation.</p>