#include #include //for the srand function and EXIT_SUCCESS #include //for the time function #include "terminal.h" #include "wolf.h" #include "rabbit.h" /* We can't delete a wabbit while the loop's iterator is still pointing to the wabbit, because the delete operator calls the wabbit's destructor, which removes the dying wabbit from the master list. And we're not allowed to increment an iterator that points to an item that has already been removed from a list. Therefore the delete must happen *after* the increment. That's why the ++it has been commented out from its usual place. */ using namespace std; int main() { srand(static_cast(time(0)));//Seed the random number generator const terminal term {'.'}; const unsigned xmax {term.xmax()}; const unsigned ymax {term.ymax()}; //The new operator calls the constructor for each wabbit, //which stores a pointer to the newborn wabbit into the master list. new wolf {term, xmax * 1 / 3, ymax * 2 / 4}; new rabbit {term, xmax * 2 / 3, ymax * 3 / 4}; new rabbit {term, xmax * 2 / 3, ymax * 2 / 4}; new rabbit {term, xmax * 2 / 3, ymax * 1 / 4}; //Loop until only the wolf still exists. for (; wabbit::master.size() > 1; term.wait(250)) { for (list::iterator it {wabbit::master.begin()}; it != wabbit::master.end(); /* ++it */) { wabbit *const p {*it}; const bool alive {p->move()}; ++it; if (!alive) { delete p; } } } term.put(0, 0, "You killed all the rabbits!"); term.wait(3000); //Give the user three seconds to read the message. //Destruct any remaining wabbits. for (list::iterator it {wabbit::master.begin()}; it != wabbit::master.end(); /* ++it */) { wabbit *const p {*it}; ++it; delete p; } return EXIT_SUCCESS; //Destruct the terminal. }