Please help, I have been working through this issue for a few hours now. I have tried using lists instead of vectors, and tried compiling it on mac os x w/ xcode, and windows VS 2010. I'm basically stumped right now.
If the object about to be erased is the last one (vector.end() -1), then ++ii
will make ii equal to vector.end().
After the erase, ii will be one past the new vector.end() - in other words ii is vector.end() + 1
- then when we get back at the top of the loop to make the test while(ii!=Fighters.end())
the test will be true because ii is not equal to Fighters.end() and we will
keep running the loop which will cause a vector out of bounds access.
** The erase function invalidates all currently held iterators - so you need to be careful here**
If an element of a vector is removed using erase method, all iterators are invalidated. That means you cannot use a previously initialized iterator to delete/access another element of the vector. Go through the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void foo (void)
{
int values[] = {1, 2, 3, 4, 5};
vector<int> v (values, values + 5);
// creates a vector with five elements
vector<int>::iterator it = v.begin ();
// The iterator points to the first element of the vector.
v.erase (it);
// First element is erased.
// The second element becomes the first element.
// All iterators are invalidated.
// i.e. iterator 'it' cannot be used any more.
it++;
v.erase (it);
// These two lines are buggy.
}
Thanks for the replies, I did not know about the invalidating, but it makes sense since vector elements are contiguous.
Also, wanted to make sure that the code would be valid if the vector was turned into a list, similarly, I use code like this in many parts of my program:
[code]
std::list<aclass> MyList;
...
list<aclass>::iterator ii=MyList.begin();
while(ii != MyList.end())
{if(ii->x == 12)
alist.erase(ii++);
else
++ii;
}
[code]