Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting while iterating [duplicate]

Tags:

c++

stl

Possible Duplicates:
Vector.erase(Iterator) causes bad memory access
iterate vector, remove certain items as I go.

Hi, I wrote this but I am get some errors when running it

for (vector< vector<Point> >::iterator track = tracks_.begin(); track != tracks_.end(); track++) {
        if (track->empty()) { // if track is empty, remove it
            tracks_.erase(track);
            track++; // is this ok?
        }else {   //if there are points, deque
            track->erase(track->begin()); //my program crashes here after a while... ;(
        }
    }

I have a vector of vector of points (2 ints) whose I call tracks (1 track is 1 vector of points) I want to check each track and if they contain points then delete the first one otherwise delete the track. Is this correct?

Thanks in advance.

like image 835
nacho4d Avatar asked Oct 10 '10 17:10

nacho4d


People also ask

Can you remove from a set while iterating?

Since we can't modify a set while iterating over it, we can create a duplicate set and remove elements that satisfy the condition from the original set by iterating over the duplicate set.

How do you remove duplicates in a for loop?

You can make use of a for-loop that we will traverse the list of items to remove duplicates. The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given.

How do you remove an element from an array while iterating in Python?

We can delete multiple elements from a list while iterating, but we need to make sure that we are not invalidating the iterator. So either we need to create a copy of the list for iteration and then delete elements from the original list, or we can use the list comprehension or filter() function to do the same.


1 Answers

A vector's erase() invalidates existing iterators, but it returns a new iterator pointing to the element after the one that was removed. This returned iterator can be used to continue iterating over the vector.

Your loop could be written like this:

vector< vector<Point> >::iterator track = tracks_.begin();
while (track != tracks_.end()) {
    if (track->empty()) {
        // if track is empty, remove it
        track = tracks_.erase(track);
    }
    else {
        //if there are points, deque
        track->erase(track->begin());
        ++track;
    }
}
like image 80
sth Avatar answered Oct 22 '22 23:10

sth