| Ok, so if I want to selectively delete items from a sequence like a
| deque or vector from a for loop, I have to do something like this:
|
| for(iter = list.begin(); iter != list.end(); ++iter)
| {
| if(shouldDelete(*iter))
| {
| iter = list.erase(iter);
| --iter;
| }
| }
Yes, but for std::deque and std::vector at least, it would be
much more efficient to use the std::remove_if algorithm:
list.erase( remove_if( list.begin(), list.end(), &shouldDelete )
, list.end() );
| I'm trying to accomplish the same sort of thing in a map traversal.
| Map's implementation of erase() doesn't return an iterator. How do I
| accomplish what I'm trying to do?
For information, see:
http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/lwg-closed.html#130
So this is a debated issue. Note that some implementations of
map::erase do return an interator. But it is quite easy to
work around this limitation: just use the postfix ++ operator.
The following will do:
for(iter = map.begin() ; iter != map.end() ; )
{
if(shouldDelete(*iter))
map.erase( iter++ );
else
++iter;
}
The map.erase( iter++ ) line is equivalent to:
{
IterType kill = iter;
++iter;
map.erase(kill);
}
(the 1-line form works because the postfix++ operator
modifies the iter variable and returns its previous
value *prior* to the call of the erase function ).
I hope this helps,
Ivan