Deleting Element from Vector with an Iterator

closed account (3bfGNwbp)
How would I do this?

1
2
3
4
5
6
7
8
9
std::vector<Bunny> v1;
std::vector<Bunny>::iterator _it;
        for(_it = v1.begin(); _it != v1.end(); ++_it) {
            if((*_it).getAge() > 5) {
                std::cout << "Bunny" << (*_it).getName() << " has died." << std::endl;
            }
            std::cout << "Bunny" << (*_it).getName() << " is now " << (*_it).getAge() << "." << std::endl;
            (*_it).newDay();
        }


I need to do something like this, but it's not working correctly.

1
2
3
if((*_it).getAge() > 5) {
        v1.erase(*_it);
}
closed account (3bfGNwbp)
Anybody? Q.Q
Hi TheBestHacker ,

Google "C++ vector example", on the left select the erase function, read all about it.

Hope this Helps

Google and wiki are your best friends.
closed account (3bfGNwbp)
v1.erase(v1.begin(), _it);

Like that? I get an access violation after it.
Reading the documentation, your last example should erase all the elements from begin up to wherever _it is. Is that what you want? I think the first version in the documentation, would suit your needs better.

You need to be careful using the iterator after erase, because they are invalidated from position to end().

Why do name variables with a leading underscore? My Personal opinion is that, it is unnecessary and harder to read.
Topic archived. No new replies allowed.