Standard way is to do something like
for(set<T>::iterator iter = s.begin(); iter != s.end();)
{
if(/*some condition*/)
{
s.erase(iter++);
}
else
{
++iter;
}
}
By the first condition we are sure, that iter
will not be invalidated anyway, since a copy of iter
will be passed into erase, but our iter
is already incremented, before erase is called.
In C++11, the code will be like
for(set<T>::iterator iter = s.begin(); iter != s.end();)
{
if(/*some condition*/)
{
iter = s.erase(iter);
}
else
{
++iter;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…