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.
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: