Removing an element from an STL list

Started by
13 comments, last by ascorbic 18 years, 10 months ago
Quote:Original post by load_bitmap_file
Quote:Original post by visage
Doesn't erase return void?


Nope.

Quote:
The return value is the element after the last element erased.


Whack. This says otherwise...which is what I was going by.
Advertisement
Quote:Original post by visage
Quote:Original post by load_bitmap_file
Quote:Original post by visage
Doesn't erase return void?


Nope.

Quote:
The return value is the element after the last element erased.


Whack. This says otherwise...which is what I was going by.


Must be outdated. SGI's pages also says erase returns an iterator.
Quote:Original post by visage
Whack. This says otherwise...which is what I was going by.


You shouldn't believe everything you read on the net. [smile]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
std::list<int>::iterator iter;for(iter = some_list.begin(); iter != some_list.end(); iter++){    if(*iter == 1)       some_list.erase(iter++); // erase and move to next item in list}


This doesn't work correctly; if it does an erase, it will increment the iterator again (by the update statement in the for loop). Look again at the code I posted, I did say 'study carefully'.
You are absolutely correct. I hate hastily changing other people's code for this reason. Change it to a while loop and all is good.

std::list<int>::iterator iter = some_list.begin();while(iter != some_list.end()){    if(*iter == 1)       some_list.erase(iter++);    else       iter++;}
.

This topic is closed to new replies.

Advertisement