openframeworks / ofBook

openFrameworks community book
706 stars 201 forks source link

oops chapter has a incorrect erase construction #274

Open ofZach opened 6 years ago

ofZach commented 6 years ago

there's a snippet in this chapter that is written like this:

for (int i =0; i < groupOfBalls.size(); i++) {
    float distance = ofDist(x,y, groupOfBalls[i].x, groupOfBalls[i].y); // a method oF gives us to check the distance between two coordinates

    if (distance < groupOfBalls[i].dim) {
        groupOfBalls.erase(groupOfBalls.begin()+i); // we need to use an iterator/ reference to the vector position we want to delete
    }
}

this is incorrect (and had a student got tripped up on this) since you are altering the vector as you delete.

either can rewrite it like this:

https://stackoverflow.com/questions/8597240/how-to-delete-an-element-from-a-vector-while-looping-over-it

I typically use lambdas now for this:

https://stackoverflow.com/questions/4478636/stdremove-if-lambda-not-removing-anything-from-the-collection

bakercp commented 6 years ago

Here is the way I approached it in my class - similar to stack overflow.

https://github.com/SAIC-ATS/ARTTECH-3135/blob/master/Session_05/03_ParticleSimpleAddRemoveForce/src/ofApp.cpp#L23-L52

That said, I was avoiding lambda's and std::remove_if in favor of covering iterators, range-for loops, etc in that example.