Search code examples
c++vectorstlerase

Erasing a specific instance of an object from a vector


I have a class Circle whose instances I keep track of with these:

Circle *f1;
vector<Circle> list;
vector<Circle>::iterator it;

I have managed to create multiple Circles and got them to move around. How can I erase a specific instance of Circle? For example, if a certain circle hits a wall, then it should be erased. I've looked around at other questions and I even tried the code they gave out and no luck. Here's what I've got at the moment:

for (it = list.begin(); it != list.end(); ++it) {

    it->x += 1;

    if (it->x == ofGetWindowWidth()) {
        list.erase(it);
    }
}

I have gotten other statements to work with the if statement such as reversing the direction of their movement. list.erase(it); was a line of code I got from here and I don't understand why it crashes my program.


Solution

  • for (it = list.begin(); it != list.end(); /* nothing here */) {
    
        it->x += 1;
    
        if (it->x == ofGetWindowWidth()) {
            it = list.erase(it);
        } else {
            ++it;
        }
    }
    

    The problem with your original code is that erasing an element invalidates the iterator to that element - the very same iterator you are trying to increment next. This exhibits undefined behavior.