about deleting in C++ STL List

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
arsalan_mousavian
Experienced poster
Posts: 111
Joined: Mon Jan 09, 2006 6:19 pm
Location: Tehran, Iran
Contact:

about deleting in C++ STL List

Post by arsalan_mousavian »

i have problem with following code

Code: Select all

for ( list<int>::iterator itr = L.begin () ; itr != L.end () ; ++ itr ) 
{ 
       if ( *itr == 2 ) L.erase ( itr ) ;
}
after the first loop ( L.erase ( itr ) ) runs a runtime error occured ( iterator not incerementable )but i have no problem when using erase function outside the loop ,seems the iterator become invalid after calling erase method
any suggestions ?
Thanks
Arsalan
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

That is precisely the reason. Use this code instead:

Code: Select all

for ( list<int>::iterator itr = L.begin () ; itr != L.end () ;){
    if ( *itr == 2 ) L.erase ( itr++ ) ;
    else ++itr;
}
Post Reply

Return to “C++”