title: Using placement new in a Vector Container
body: <p>If I have a container:</p>
  
  <pre><code>std::vector&lt;T*&gt; elements;
  </code></pre>
  
  <p>can I use placement new to allocate my objects so that the objects are all allocated contiguously? So that I can do something like this:</p>
  
  <pre><code>size_t elementIndex = someRandomElement - elements[0];
  </code></pre>
  
  <p>Where <code>someRandomeElement</code> is a random element from <code>elements</code> and <code>elementIndex</code> will then store the correct index of <code>someRandomElement</code> so that <code>elements[elementIndex] == someRandomElement</code></p>
  
  <p>This is needed for my current implementation of a memory manager. I have an implementation that I was able to finish today, but it requires the elements (which can be a voxel, a triangle or anything else) to have GetIndex() and SetIndex() function so that when the element is returned as a pointer, I can find out the index of the element in the <code>elements</code> array, which means that any elements that I cannot change (let's say Ogre::Vector3) cannot use the manager (in my case, I need them to use it because they are fragmenting the memory). </p>
  
  <p>My only other solution is to have a structure that acts as an accessor and has the index as well as the pointer to the element although this will result in an increased memory usage (considering I am working with 5 million elements right now).</p>
  
  <blockquote>
    <p>NOTE: There is a <a href="https://stackoverflow.com/q/5747455/368599">similar question</a> that I posted today, but the answers there are making some assumptions which go totally against my requirements. One of the requirement is that the vector must be filled with pointers to <code>T</code> otherwise a large portion of the code-base needs to change. Secondly, initializing more than 100,000 (approximately) elements results in a bad_alloc exception. Each element is 196 bytes in size (I have managed to reduce that to 132 bytes). </p>
  </blockquote>