Re: Deleting an element from a list in a loop
Thanks!
"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message
news:uq8af29f0antihmum7pvjclm9jsed5etpl@4ax.com...
On Wed, 30 Aug 2006 00:09:09 -0500, "Andrew Chalk"
<achalk@magnacartasoftware.com> 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