Vector iterator not decrementable

I thought I was being smart by switching over to newer style vector iterator for loops but now that I am porting my code to windows from OSX (where it ran perfectly) I am getting the error “Vector Iterator not Decrementable” and the sketch fails to run.

I have read some of the related posts and they all seem to be slightly different use cases. I liked this style of for loop because it allowed me to use reference to the instance easily. I guess I either need to know if there is a solution or if I need to switch back to a regular for loop.

for(std::vector<car>::iterator it = cars.begin() ; it != cars.end(); ++it) {
    (*it).wander();
    (*it).arrive();
    (*it).update(maxSpd, alphaTagetAng);
    trail.setVertex((*it).leadVert, (*it).location);
    if(frame%3==0){
        trail.addVertex((*it).location);
        col = ofColor(ofRandom(100,200),ofRandom(100,200), ofRandom(100,200), 40);
        col = ofColor(col.r*tint.x,col.g*tint.y, col.b*tint.z, col.a*1.0 );
        trail.addColor(col);
        (*it).leadVert = trail.getNumVertices()-1;
    }
    if(trail.getNumVertices()>2500) {
        trail.removeVertex(0);
        trail.removeColor(0);
    }
    if (!(*it).life) {
        //ofRemove(cars, kill);
        cars.erase(it); //<---------------Problem
        //playMe = true;
        it--;
    }
}

i would use instead:

cars.erase(std::remove_if(cars.begin(), cars.end(), [&](Car & car){
    car.wander();
    car.arrive();
    car.update(maxSpd, alphaTagetAng);
    trail.setVertex(car.leadVert, car.location);
    if(frame%3==0){
        trail.addVertex(car.location);
        col = ofColor(ofRandom(100,200),ofRandom(100,200), ofRandom(100,200), 40);
        col = ofColor(col.r*tint.x,col.g*tint.y, col.b*tint.z, col.a*1.0 );
        trail.addColor(col);
        car.leadVert = trail.getNumVertices()-1;
    }
    if(trail.getNumVertices()>2500) {
        trail.removeVertex(0);
        trail.removeColor(0);
    }
    return !cars.life;
}), cars.end());

which avoids directly dealing with the individual iterators, having to dereference them and it’s also faster since remove_if doesn’t need to move the remaining of the vector every time you erase one element but instead swaps the elements to be removed to the end of the vector and then cars.erase() just needs to resize the vector to the last valid element.

Arturo,
holy crap. I get how it works, but would never have gotten there. Thank you so much for the code!!
Any thoughts on why this worked on OSX but not windows?

not 100% sure but i guess the vs compiler has some more checks on iterators, might be that it detects that the iterator has been deleted and won’t let you decrease it cause it’s been invalidated or that in certain paths like the first iteration you are going to go beyond the vector boundaries by decreasing it which would be illegal in principle and might have crashed at run time in debug where visual studio does boundary checks