title: Any better alternative to std::vector<std::unique_ptr<T>>?
body: <p>I'm looking for a container <em>(targeted towards game-development, especially for entity management)</em> that needs to satisfy these requirements:</p>
  
  <ol>
  <li><strong>Fast iteration</strong></li>
  <li><strong>No copies of stored elements</strong> </li>
  <li><strong>No invalidation of pointers to the elements</strong></li>
  <li><strong>Removal and insertion of elements</strong></li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>Container&lt;Entity&gt; container;
  
  // This pointer will always point to the player
  Entity* player{new Entity};          
  container.add(player);               
  
  // Set some entities to "dead"
  for(auto&amp; e : container) if(e-&gt;type == "Enemy") e-&gt;die(); 
  
  // Use erase-remove idiom on "dead" entities
  container.cleanup();                 
  
  // Player pointer is still valid
  player-&gt;doSomething();               
  </code></pre>
  
  <hr>
  
  <p>I've tried two different container types so far:</p>
  
  <ul>
  <li><code>std::vector&lt;std::unique_ptr&lt;T&gt;&gt;</code>
  
  <ol>
  <li><strong>Cache-friendly</strong> (fast iteration)</li>
  <li><strong>No copies</strong> (thanks to <code>std::unique_ptr</code>)</li>
  <li><strong>No invalidation of pointers</strong> (thanks to <code>std::unique_ptr</code>)</li>
  </ol></li>
  </ul>
  
  <p>...and...</p>
  
  <ul>
  <li><code>std::list&lt;T&gt;</code>
  
  <ol>
  <li><strong>Non cache-friendly</strong> (slower iteration)</li>
  <li><strong>No copies</strong></li>
  <li><strong>No invalidation of pointers</strong></li>
  </ol></li>
  </ul>
  
  <p>Even if it seems counter-intuitive, <code>std::vector&lt;std::unique_ptr&lt;T&gt;&gt;</code> is more performant than <code>std::list&lt;T&gt;</code> <a href="https://gist.github.com/SuperV1234/8098965" rel="noreferrer">according to my benchmarks</a>. </p>
  
  <p><em>(For bigger types, <code>std::list&lt;T&gt;</code> is more performant during insertion, but <code>std::vector&lt;std::unique_ptr&lt;T&gt;&gt;</code> still wins)</em>.</p>
  
  <hr>
  
  <p>I was wondering if there is a better alternative to <code>std::vector&lt;std::unique_ptr&lt;T&gt;&gt;</code>.</p>
  
  <p>Ideally, the alternative should be <strong>cache-friendly</strong>, for fast iteration, and allow the user to refer to the same items even after adding/removing existing items <strong>(pointers should not be invalidated)</strong>.</p>