Iterate through a vector and delete elements?

So, I'm trying the bunny game exercise from http://www.cplusplus.com/forum/articles/12974/.

I'm trying to iterate through all the bunnies in existence and then remove ones that are too old from the vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
for (iter = bunnyList.begin(); iter != bunnyList.end();
        iter++)
    {
        iter->age++;    // age all bunnies. 
        
        // The problem is here, I think
        if (iter->tooOld())
        {
            cout << iter->name << " died!" << endl;
            bunnyList.erase(iter);   // kill the bunny
        }
        // -----------------------------
        
        if (iter->age >= 2 && iter->gender == female)
        {
            if (dadExists)
                bunnyList.push_back(iter->BirthBunny(*iter)); // add that bunny to the list.
        }

        if (numRMVB > 0)
        { 
            if (!iter->isRMVB)  // if the current is not an RMVB.
            {
                sampleRMVB.ConverttoRMVB(*iter);
                numRMVB--;
            }            
        }
    }


I'm guessing that erasing a bunny is messing with the vector iterator..if so, how can I fix this? I tried google, but all the examples I've found seem to require that you already know the location of the element you want to delete.

Edit: Forgot to mention that this is a runtime error, not a compiler error. The program usually ends up crashing after a bunch of bunny-deaths in a row. If you want, I can post the output.
Last edited on
After you erase with iterator, all current iterators are invalided (with std::vector anyway). .erase() returns the next valid iterator, so you can use that to keep iterating if you want.
so should I be writing iter = bunnyList.erase(iter); at line 10?
yes
Alright, thanks - still having strange problems, but I'll try working at this more before posting again. :)
One problem is that if you do erase an item, you don't want to then perform all the other tests because you have selected a different element. Also you don't want to increment the new iterator before sending it through the loop again. So you have a flow problem to sort out.
Oh and also line 17 invalidates your iterator by adding more bunnies to the list. I would be tempted to add the new bunnies to a separate list and when the loop is over, append the new bunnies to the main list.
Topic archived. No new replies allowed.