Thread: iterator aftermath of editing a list

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    5

    iterator aftermath of editing a list

    What happens to an STL iterator when the list it is referring to changes, by adding and erasing elements (that are of course not being currently pointed by the iterator)? Is it still valid to use and erase the element pointed by the iterator? What I am really interested in is if the following code is legal:

    Code:
    #include <list>
    #include <iostream>
    using namespace std;
    
    int main() {
    	list<int> fooList;
    	list<int>::iterator iter;
    
    	fooList.push_back(1);
    	fooList.push_back(2);
    
    	iter = fooList.begin();
    	iter++; // point at the element with value 2
    
    	// do some changes to other elements of the list
    	fooList.pop_front();
    	fooList.push_back(3);
    	
    	// the list has changed, but is this still ok?
    	fooList.erase(iter);
    
    	return 0;
    }
    The code runs fine but I wish to make sure its not just on my platform/implementation.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yes, I believe it is. You have to be careful about that stuff, but for lists, I believe iterators are not invalidated by calls that insert or erase (unless the element referred to by the iterator is erased).

    ... confirmed by a quick look at Josuttis The C++ Standard Library section 6.4.1.
    Last edited by Daved; 01-24-2006 at 06:17 PM.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    5
    OK, thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  2. instantiated from here: errors...
    By advocation in forum C++ Programming
    Replies: 5
    Last Post: 03-27-2005, 09:01 AM
  3. List class
    By SilasP in forum C++ Programming
    Replies: 0
    Last Post: 02-10-2002, 05:20 PM
  4. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM