0

Why am I getting a Vector iterator is not incrementable error in this code?

for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); ++it) {
    if (contourArea(*it) < 50) {
        it = contours.erase(it);
    }
}

The other answers I looked at said to solve this error by assigning the iterator that .erase() returns to it, but I'm still getting the same error. What's wrong?

Matt
  • 2,232
  • 8
  • 35
  • 64

1 Answers1

4

Your code has two problems:

  1. It skips an element when you erase an element.
  2. It runs in to a problem (leading to undefined behavior) if you call erase on the last element of the vector.

Here's what you should use:

for (vector<vector<Point>>::iterator it = contours.begin(); it != contours.end(); ) {
    if (contourArea(*it) < 50) {
        it = contours.erase(it);
    }
    else {
        ++it;
    }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270