Jump to content

  • Log In with Google      Sign In   
  • Create Account

#ActualJosh Klint

Posted 03 May 2013 - 09:56 PM

Has anyone found a way to remove any item from a list as it is iterating?

Normally a loop to iterate through a linked list looks like this:

for ( it = list.begin(); it != list.end(); it++ )
{
}

 

 

If you want to be able to remove an item from the list while it is iterating, you can always do this:

it = list.begin();
while (it != list.end() )
{
	if (condition)
	{
		it = list.erase(it);
	}
	else
	{
		it++;
	}
}

 

 

But what if the code in your loop called other code that could result in the removal of the object from the list, with no way to tell it occurred? It could also result in removing other objects from the list, with no way of knowing it happened. In that case, our previous trick would not be enough to prevent any possible problems, because the code might be removing the next item in the list after we have forwarded the iterator.

Has anyone come up with a solution to this?


#1Josh Klint

Posted 03 May 2013 - 09:56 PM

Has anyone found a way to remove any item from a list as it is iterating?

Normally a loop to iterate through a linked list looks like this:

for ( it = list.begin(); it != list.end(); it++ )
{
}

If you want to be able to remove an item from the list while it is iterating, you can always do this:

it = list.begin();
while (it != list.end() )
{
	if (condition)
	{
		it = list.erase(it);
	}
	else
	{
		it++;
	}
}

But what if the code in your loop called other code that could result in the removal of the object from the list, with no way to tell it occurred? It could also result in removing other objects from the list, with no way of knowing it happened. In that case, our previous trick would not be enough to prevent any possible problems, because the code might be removing the next item in the list after we have forwarded the iterator.

Has anyone come up with a solution to this?


PARTNERS