• Advertisement
Sign in to follow this  

std list and erase while in a loop

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I am looping through a list, and erasing the element I am at. Then move onto the element after the removed element. Something like this:
list<RECT>::iterator itCheckRECT=lstRects.begin();
while( itCheckRECT!=lstRects.end() )
{
	//check if rects overlap						
	bool bResult=rectOverlap(RECTa,RECTb);
	if(bResult==true)
	{											//do stuff
		recClosestRect.top=RECTb.top;							recClosestRect.left=RECTb.left;							recClosestRect.right=RECTb.right;						recClosestRect.bottom=RECTb.bottom;

		itCheckRECT=lstRects.erase(itCheckRECT);
		++itCheckRECT;
	}
	else
	{
                //do other stuff
		itCheckRECT=lstRects.erase(itCheckRECT);
		++itCheckRECT;
	}
}

My problem is that instead of going to the next item in the list it skips an element, eg shown in order when looping:
checkRect Top=0 Left=0 Right=256 Bottom=32       //1st
checkRect Top=32 Left=0 Right=128 Bottom=160     //skipped   //4th
checkRect Top=32 Left=128 Right=256 Bottom=64    //2nd
checkRect Top=64 Left=128 Right=192 Bottom=128   //skipped   //missed completely
checkRect Top=64 Left=192 Right=224 Bottom=192   //3rd

It does erase the elements I want it to though. Anyone able to help?

Share this post


Link to post
Share on other sites
Advertisement
Yes. You don't need to increment the iterator you get from an erase. That iterator will already be pointing to the next element after the erased one.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement