Deleting elements from a STL List conditionally

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dariophoenix
    New Member
    • Oct 2006
    • 34

    Deleting elements from a STL List conditionally

    Hi,
    We¡re getting a segmentation fault because we¡re trying to delete elements from a List while traversing it, i.e.:

    Code:
    void Character::deleteProcessed(list<Line> &active,int y){
    	bool erasedAtTheEnd = false;
    	for (list<Line>::iterator it = active.begin();it != active.end()&&!erasedAtTheEnd;){
    		if (it->getHighPoint().getY() < (HeightFloat/Height)*(y+1)){
    			Line aux = *it;
    			it++;
    			//In case you try to delete the final element ,  it != end  doesn't 
                            //stop the loop
    			if (it==active.end()) 
    				erasedAtTheEnd = true;
    			active.remove(aux);
    		}
    		else it++;
    	}
    }
    Last edited by dariophoenix; Nov 21 '06, 07:11 PM. Reason: Burnout
  • Colloid Snake
    New Member
    • Nov 2006
    • 144

    #2
    I know for sure in Java(not 100% sure about C++), that when you declare an iterator and use it to traverse a list, you cannot manipulate the list, by design. Have you tried a for loop with a counter that is cast as a 'Line' object to traverse the list? That might let you bypass (if it is the same in C++ as Java) the whole iterator/manipulation thing.

    Comment

    Working...