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.
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.
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.