tags:

views:

101

answers:

2

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.

+2  A: 

I'm not sure what errors you're getting, but chances are that you're invalidating your iterator.

You should read http://www.angelikalanger.com/Conferences/Slides/CppInvalidIterators-DevConnections-2002.pdf

Specifically, vector::erase invalidates all iterator and references to elements after position or first.

David Titarenco
+7  A: 

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;
    }
}
sth