0

im new to C++. I want to know how to erase an element from a vector passed by reference, where the value of Length (function of my Vector3D object) returned is less than the int parameter passed to the function.

void Util::removeLessThan(vector<Vector3D> &vectors, int lessThan) {

    vector<Vector3D>::iterator it;

    for(it = vectors.begin(); it != vectors.end(); it++) {
        if(it->Length() < lessThan) {
            vectors.erase(it);
        }

    }
}

It seems like it only deletes a couple of elements from the vector. Here is an output:

vector before i run the removeLessThan func:

22.561
17.3781
12.2066
7.07107
3.74166

vector after i run the removeLessThan func:

7.07107
12.2066
17.3781
22.561

I read something about the iterator becoming invalidated after after running erase, but i cannot really grasp how to work around this.

Someone cares to explain to a beginner?

Thanks!

king_nak
  • 11,313
  • 33
  • 58
  • You must not increment your iterator after `erase`. To avoid UB, you also have to use `it = blah.erase(it);`. Solution: Replace the `if` with `while (it->Length() < lessThan) {it = vectors.erase(it);}`. – HolyBlackCat Feb 08 '18 at 11:29
  • Thanks alot, it worked. Doesent quite make sense to me though, replacing a while loop with an if statement. :-P –  Feb 08 '18 at 11:39
  • Note the suggestion from HolyBlackCat only works because your vector has been sorted. – UKMonkey Feb 08 '18 at 11:41

0 Answers0