How do I avoid pointer invalidation in my insert function?
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.
Here are my insert function, and reserve function:
// Insert "item" before "pos", and return iterator referencing "item"
iterator insert (iterator pos, const T& 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 < 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;
}
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 pr开发者_如何学Gooblem?
Change the pos
iterator into an index instead, and use that.
size_t index = pos - begin();
// do resize
pos = begin() + index;
If you're worried about iterators invalidating in general, don't. It's unavoidable, at least in this style of dynamic array, and std::vector
works exactly the same.
精彩评论