title: How to properly work with vectors of pointers?
body: <p>If I have a vector of objects, for example:</p>
  
  <pre><code>std::vector&lt;Foo&gt; foos;
  
  for(int i = 0; i &lt; 10; i++) {
      foos.push_back(Foo());
  }
  </code></pre>
  
  <p>and lets say I distinguish them in different kind of <code>Bar</code>s, each with a vector of <code>Foo</code>s:</p>
  
  <pre><code>std::vector&lt;Bar&gt; bars;
  
  bars.push_back(Bar());
  bars.push_back(Bar());
  
  for(int i = 0; i &lt; 5; i++)
      bars.at(0).addFoo(foos.at(i));
  
  for(int i = 5; i &lt; 10; i++)
      bars.at(1).addFoo(foos.at(i));
  </code></pre>
  
  <p>If I now do for example <code>foos.at(0).setValue(1)</code>, <code>bars.at(0).getFoo(0).getValue()</code> would not be 1, so I have to create pointers:</p>
  
  <pre><code>std::vector&lt;Bar&gt; bars;
  
  bars.push_back(Bar());
  bars.push_back(Bar());
  
  for(int i = 0; i &lt; 5; i++)
      bars.at(0).addFoo(&amp;foos.at(i));
  
  for(int i = 5; i &lt; 10; i++)
      bars.at(1).addFoo(&amp;foos.at(i));
  </code></pre>
  
  <p><code>bars.at(0).getFoo(0).getValue()</code> would now return 1.</p>
  
  <p>But how do I clean those pointers properly?  </p>
  
  <ul>
  <li>If I do <code>foos.pop_back()</code>, how can I make that automatically the last Foo pointer in <code>bars.at(1)</code> will get deleted? Because in my program I sometimes wouldn't know where in the <code>bars</code> vector the pointer to the exact object is.</li>
  <li>If I do <code>bars.at(1).removeLastFoo()</code>, the object would ofcourse (and also should) stay alive in <code>foos</code>. Would <code>removeLastFoo()</code> just delete the last pointer of <code>Bar</code>s vector of <code>Foo</code>s and pop it?</li>
  <li>If I do <code>bars.pop_back</code>, do I have to write in <code>Bar</code>s destructor to delete every single pointer out of it?</li>
  </ul>
  
  <p>If I have forgotten something, please tell me.</p>
  
  <p>Or is there a more elegant way (I actually prefer not to use pointers but I see no other way) to be able to see the same changes at different locations?</p>