Re: Deleting an element from a list in a loop

Tech-Archive recommends: Fix windows errors by optimizing your registry



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


.



Relevant Pages

  • Re: Deleting an element from a list in a loop
    ... the internal pointers? ... call erase() in the loop: ... // Do we need to break out of the loop here? ... Visual C++ MVP ...
    (microsoft.public.vc.stl)
  • Deleting an element from a list in a loop
    ... Will deleting an element from a list while iterating through a loop mess up ... the internal pointers? ...
    (microsoft.public.vc.stl)
  • Re: Vb 2003 Framework 1.1
    ... >> Armin before i send the document can you help me out on this for ... >> loop .when i do the following loop and code for the initial loop ... The "Erase Table Request" provides a means for the master to clear ... Dim result As Byte ...
    (microsoft.public.dotnet.languages.vb)
  • Re: how do I use macro to find and replace unicode characters
    ... While I have been honored with an MVP designation from Microsoft, you should know that MVPs are not employees of Microsoft... ... Dim C As Range ... ' FindNext methods will operate on (the UsedRange of Sheet1). ... so we need to loop three times incrementing ...
    (microsoft.public.excel.misc)
  • Re: Remove zero from first letter
    ... Bob Barrows [MVP] wrote: ... loop part, i mean there is debug in loop code, the loop is not ... Function StripLeadingChars(byval original as string, ... Please reply to the newsgroup. ...
    (microsoft.public.access.queries)