Re: Deleting an element from a list in a loop
- From: "Andrew Chalk" <achalk@xxxxxxxxxxxxxxxxxxxxxx>
- Date: Wed, 30 Aug 2006 01:51:36 -0500
Thanks!
"Doug Harrison [MVP]" <dsh@xxxxxxxx> wrote in message
news:uq8af29f0antihmum7pvjclm9jsed5etpl@xxxxxxxxxx
On Wed, 30 Aug 2006 00:09:09 -0500, "Andrew Chalk"
<achalk@xxxxxxxxxxxxxxxxxxxxxx> wrote:
Will deleting an element from a list while iterating through a loop mess
up
the internal pointers? I am thinking of a construct such as this where I
call erase() in the loop:
for (;it != m_list.end(); it++) {
if ((*it)->ThreadFinished() == true) {
...DO STUFF
m_list.erase(it); // delete the element from the list
// Do we need to break out of the loop here?
}
}
Erasing a list element invalidates iterators, references, and pointers to
the item erased, so you need to structure your loop like this:
while (it != m_list.end())
{
if ((*it)->ThreadFinished()) // Don't compare against true or false
{
it = m_list.erase(it);
// or m_list.erase(it++);
}
else
++it;
}
--
Doug Harrison
Visual C++ MVP
.
- References:
- Deleting an element from a list in a loop
- From: Andrew Chalk
- Re: Deleting an element from a list in a loop
- From: Doug Harrison [MVP]
- Deleting an element from a list in a loop
- Prev by Date: Re: Deleting an element from a list in a loop
- Next by Date: Re: Deleting an element from a list in a loop
- Previous by thread: Re: Deleting an element from a list in a loop
- Next by thread: Re: Deleting an element from a list in a loop
- Index(es):
Relevant Pages
|