WhatMeWorry
2005.05.05, 11:26 AM
Many times I've come across the following caveat:
"Be careful if you erase() or insert() elements in the middle of a vector. This can invalidate all existing iterators."
And I played around with an STL loop in the following general form:
// extremely rough pseudo code from memory
vector c; terator i
for ( i = c.begin, i = c.end, i++)
{
if (i == something)
{
c.erase(i)
}
}
And sure enough, the iterator was screwed up after the erase().
OK, so is there a preferred method (idiom) for dealing with the
invalidation of the iterator after the erase() of insert()?
One quick and dirty fix that I did was to put a break command after the
c.erase which would exit the loop. Was wondering if there was a
better approach. Maybe the above form is not even recommended?
"Be careful if you erase() or insert() elements in the middle of a vector. This can invalidate all existing iterators."
And I played around with an STL loop in the following general form:
// extremely rough pseudo code from memory
vector c; terator i
for ( i = c.begin, i = c.end, i++)
{
if (i == something)
{
c.erase(i)
}
}
And sure enough, the iterator was screwed up after the erase().
OK, so is there a preferred method (idiom) for dealing with the
invalidation of the iterator after the erase() of insert()?
One quick and dirty fix that I did was to put a break command after the
c.erase which would exit the loop. Was wondering if there was a
better approach. Maybe the above form is not even recommended?