CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2008
    Posts
    902

    Erase element from std::list, old iterators still valid?

    Lest say I have a std::list of items, and some of these items are being tracked by an iterator held someplace else. If I remove an element from the list, are these iterators still valid?

  2. #2
    Join Date
    May 2009
    Posts
    2,413

    Re: Erase element from std::list, old iterators still valid?

    Yes for std::list they are. If you insert or delete an element iterators to other elements are still valid. See The C++ Standard Library, a Tutorial and Reference by Josuttis (p. 167).

    Still, I generally play it safe and assume all iterators get invalidated whenever a container is restructured.
    Last edited by nuzzle; May 23rd, 2011 at 12:56 AM.

  3. #3
    Join Date
    Oct 2006
    Posts
    616

    Re: Erase element from std::list, old iterators still valid?

    See here:

    "Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed.

    The ordering of iterators may be changed (that is, list<T>::iterator might have a different predecessor or successor after a list operation than it did before), but the iterators themselves will not be invalidated or made to point to different elements unless that invalidation or mutation is explicit."

    Regards,
    Zachm

  4. #4
    Join Date
    Aug 2008
    Posts
    902

    Re: Erase element from std::list, old iterators still valid?

    Thanks, Zachm.

    I'm afraid I have to rely on that property of std::list, so I can't play it safe.

  5. #5
    Join Date
    May 2009
    Posts
    2,413

    Re: Erase element from std::list, old iterators still valid?

    Quote Originally Posted by Chris_F View Post
    Thanks, Zachm.
    Was there something wrong with my reply?

    I'm afraid I have to rely on that property of std::list, so I can't play it safe.
    Restructuring while processing is the programming equivalent of sawing off the branch one is sitting on. There's almost always a better option available.
    Last edited by nuzzle; May 23rd, 2011 at 09:08 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured