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.
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With