title: C++ vector dynamic memory deallocation/delete
body: <p>When I try and delete dynamic memory elements of a dynamic vector of objects, I have to iterate over the entire size of the vector more than once to ensure complete deallocation.</p>
  
  <pre><code>class CV{
      public:
              float x;
              float y;
  
              CV();
              CV(float, float);
              ~CV();
   };
  
  
  int main(){
  
      vector&lt;CV*&gt;* cars;
      cars = new vector&lt;CV*&gt;;
  
  
      //create objects with new, push into vetor
      for(int j=0;j&lt;4;j++){
              cars-&gt;push_back( new CV(10.0+j, 11.99+j) );
      }
  
      while( cars-&gt;size() &gt; 0   ){
              for(int i=0;i&lt;cars-&gt;size();i++){
                      delete (*cars)[i];
                      cars-&gt;erase( cars-&gt;begin()+i);
              }
              cout &lt;&lt; "size:"&lt;&lt; cars-&gt;size() &lt;&lt; endl;
      }
  
      delete cars;
      return 0;
  
  }
  </code></pre>
  
  <p>This will output:</p>
  
  <pre><code>  size:2
    size:1
    size:0
  </code></pre>
  
  <p>The vector seems to iterate over every second element when I try to delete, as I require the extra while loop to ensure total deallocation.</p>
  
  <p>I seem to be missing something about the internal workings of vector, I've tried reading the vector c++ reference and I understand that vectors store elements in a contiguous location and that they allocate extra storage for possible growth, but I fail to understand the behaviour of this code.</p>