erasing a vector element with an iterator

The following code causes a debug assertion in the vector class when trying to increment the iterator after the if statement is true and erase is called.

Does calling erase on the iterator destroy the iterator itself? I thought it just erased the element which it points to, but it is unusable after a call to erase.

1
2
3
4
5
for ( std::vector<PSet>::iterator it = ps_.begin(); it != ps_.end(); ++it )
{
       	if ( it->contains(row,col) )
	    ps_.erase(it);
}


Thanks muchly.
As you mentioned, erase() invalidates iterators (at least for vectors)

The solution here is to use the returned value from erase():

1
2
3
4
5
6
7
8
9
std::vector<PSet>::iterator it = ps_.begin();

while(it != ps_.end())
{
    if ( it->contains(row,col) )
        it = ps_.erase(it);
    else
        ++it;
}
Last edited on
ah great thanks Disch
Topic archived. No new replies allowed.