Using iterator in lists in c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//suppose oblist has three values 100 , 90 , 11921
    for(O=Oblist.begin();O!=Oblist.end();++O){

    if((O->Obstacle_ID) == 100 || (O->Obstacle_ID) == 90 || (O->Obstacle_ID) == 11921 ){
       //Oblist.remove(100);
        O = Oblist.erase(O);
        //Oblist.remove_if(O->Obstacle_ID == 100);
 if(O == Oblist.end())
		 {
		 break;
		 }
    }
    cout<<"\nNew List Values\n";
    for(O=Oblist.begin();O!=Oblist.end();++O)
    {
        cout<<"\n"<<O->Obstacle_ID;
    }
    cout<<"\n";

I was having an error while using an iterator and i was suggested on a forum to use
1
2
3
4
if(O == Oblist.end())
		 {
		 break;
		 }

For checking if it is in the end or not and if it is in the end then it will not give me an "Assertion failed" error, i did that and it worked perfectly but the thing is using this funciton i am always left with one value behind, which is not what i want, what if i want to delte all the values , obviously I can need to delete all the values from list also based on a specific decision, what should i do if i wana do that. i reposted it on that forum but since 2 days didnt get any answer, and i am already getting late. what can i do to do so. i mean i want that if i delete all values it's iterator should not come up with error or so .
Problem here is that O = Oblist.erase(O); will make O refer to the next element and ++O will advance the iterator one step further so you never handle the element after the erased element.

A better way is to use a while loop so that you can do ++O only when ease wasn't used.

1
2
3
4
5
6
7
8
9
10
11
12
O=Oblist.begin();
while (O !=Oblist.end())
{
	if ((O->Obstacle_ID) == 100 || (O->Obstacle_ID) == 90 || (O->Obstacle_ID) == 11921 )
	{
		O = Oblist.erase(O);
	}
	else
	{
		++O;
	}
}

Last edited on
Great Great Great !
It works, My First problem posted on this forum and a quick solution.
Wow I am Happy to get to know such a forum
Regards Imran
Topic archived. No new replies allowed.