How do I avoid pointer invalidation in my insert function?
<p>In my data structures course, we are creating a basic vector class. In my header, there is a member function for inserting new values into the vector. If the capacity of my vector is big enough for the insertion of one value, the program runs fine. However, if the vector needs to grow, I run into pointer errors. After hours of trying to figure out what was happening, I believe that I'm running into a problem with invalidating iterators.</p>

<p>Here are my insert function, and reserve function:</p>

<pre><code>// Insert "item" before "pos", and return iterator referencing "item"

iterator insert (iterator pos, const T&amp; item)
{

if (m_size ==  m_capacity)
  {
  reserve(m_capacity * 2);
  }

T * endOfArray = (end());

while (endOfArray != pos)
  {
  *(endOfArray) = *(endOfArray - 1);
  --endOfArray;
  }
++m_size;
*pos = item;

return (pos);
}

void reserve (size_t space) {
if (space &lt; m_capacity)
  {
  return;
  }

T *temp_array = new T[space]; 

std::copy(begin(), end(), temp_array);
m_array = new T[space];
std::copy(temp_array, (temp_array + m_size), m_array);
m_capacity = space;
delete [] temp_array;
} 
</code></pre>

<p>As you can see, if the insert function calls to have the capacity of the vector increased, then the "pos" iterator invalidates. How can I get around this problem?</p>
