title: C++ Vector Iterator: Compare and Erase Two Elements
body: <p>I have a <code>std::vector&lt;Shape*&gt;</code> called scene which stores pointers to Shapes. I need to be able to iterate through the vector, comparing the shape pointed to by the iterator with the next shape in the iterator. If the return of <code>s1-&gt;intersects(*s2)</code> is true, I need to remove both s1 and s2 from the vector. The following code isn't correct, I get an exception <code>vector interator is not incrementable</code>. </p>
  
  <p>How can I solve this problem?</p>
  
  <pre><code>while (scene.size() &gt; 1)
  {
      for (std::vector&lt;Shape*&gt;::iterator it = scene.begin(); it != scene.end() - 1; it++)
      {
          Shape* s1 = (*it);
          Shape* s2 = (*(it + 1));
  
          if (s1-&gt;intersects(*s2))
          {
              delete s1;
              delete s2;
  
              // Remove the pointers to s1 and s2 from the vector.
              it = scene.erase(it);
              it = scene.erase(it);
          }
      }
  }
  </code></pre>