title: C++ iterator behaviour in for vs while loops
body: <p>I do not understand why iterating through a container with a for loop produces different results than iterating through it with a while loop. The following MWE illustrates this with a vector and a set of 5 integers.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;set&gt;
  using namespace std;
  
  int main()
  {
    vector&lt;int&gt; v;
    set&lt;int&gt; s;
  
    // add integers 0..5 to vector v and set s
    for (int i = 0; i &lt; 5; i++) {
      v.push_back(i);
      s.insert(i);
    }
  
    cout &lt;&lt; "Iterating through vector with for loop.\n";
    vector&lt;int&gt;::const_iterator itv;
    for (itv = v.begin(); itv != v.end(); itv++) cout &lt;&lt; *itv &lt;&lt; ' ';
    cout &lt;&lt; '\n';
  
    cout &lt;&lt; "Iterating through set with for loop.\n";
    set&lt;int&gt;::const_iterator its;
    for (its = s.begin(); its != s.end(); its++) cout &lt;&lt; *its &lt;&lt; ' ';
    cout &lt;&lt; '\n';
  
    cout &lt;&lt; "Iterating through vector with while loop.\n";
    itv = v.begin();
    while (itv++ != v.end()) cout &lt;&lt; *itv &lt;&lt; ' ';
    cout &lt;&lt; '\n';
  
    cout &lt;&lt; "Iterating through set with while loop.\n";
    its = s.begin();
    while (its++ != s.end()) cout &lt;&lt; *its &lt;&lt; ' ';
    cout &lt;&lt; '\n';
  }
  </code></pre>
  
  <p>The above produces:</p>
  
  <pre><code>Iterating through vector with for loop.
  0 1 2 3 4 
  Iterating through set with for loop.
  0 1 2 3 4 
  Iterating through vector with while loop.
  1 2 3 4 0 
  Iterating through set with while loop.
  1 2 3 4 5 
  </code></pre>
  
  <p>The for loops work as expected but not the while loops. Since I'm using <code>++</code> as a postfix, I don't understand why the while loops behave as they do. Another mystery is why the while loop prints a <code>5</code> for set <code>s</code>, since this number was not inserted in <code>s</code>.</p>