Monday, April 6, 2009

elegant way to erase a node from an iterating list

It is always puzzle me why erasing a stl node inside a loop is so troublesome, example:

for (i = List.begin(); i != List.end(); )
{
temp_i = i; // to prevent the "chain" breaks by the erased node
++i;
List.erase(temp_i);
delete *temp_i;
}

There is a more elegant way to do the similar thing

for (i = List.begin(); i != List.end(); )
{
delete *i;
i = List.erase(i); // return element that followed the last element erased by the function call
}

elegant right?

No comments: