What's wrong with this?

main.cpp:
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
29
#include <iostream>
#include <string>
#include <ctime>
#include <list>
#include "bunny.h"

int main(void) {
    int counter = 1;
    srand(time(NULL));
    std::list<Bunny> bContainer;
    std::list<Bunny>::iterator iter;
    bContainer.push_back(Bunny("Ricky"));
    bContainer.push_back(Bunny("Jessica"));
    while(bContainer.size() > 0) {
        std::cout << "Year #" << counter++ << '\n' << std::string(18, '-') << std::endl;
        for(iter = bContainer.begin(); iter != bContainer.end(); ++iter) {
            iter->newYear();
            if(iter->getAge() >= 15) {
                std::cout << iter->getName() << " is now dead." << std::endl;
                iter = bContainer.erase(iter);
            }
            else {
                std::cout << iter->getName() << " is now " << iter->getAge() << '.' << std::endl;
            }
        }
        std::cin.get();
    }
    return 0;
}

bunny.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Bunny {
	private:
		bool gender;
		unsigned age;
		std::string name; 
	public:
		// (COPY) CONSTRUCTORS
		Bunny(void);
		Bunny(const std::string);
		// GETTER METHODS
		std::string getName   (void) const { return name;   }
		unsigned    getAge    (void) const { return age;    }
		bool        getGender (void) const { return gender; }
		// OTHER METHODS
		void        newYear   (void)       { ++age;         }
		// OVERLOADED OPERTORS
};

Bunny::Bunny(void) { }
Bunny::Bunny(const std::string n) : name(n), age(0), gender(rand() % 2) { }

Picture: http://imgur.com/A93PL

They don't all die at the same time even if they are 15 years old. The bunnies only die one at a time. Why is that?
Last edited on
Line 20 positions iter at the node following the one you just erase()d. At the end of the iteration, the ++iter on the for skips that node entirely.
You can easily fix this by decrementing iter immediately after erasing the node.

PS: By the way, you didn't need to post a screenshot. Just pasting your program's output here would have sufficed.
Last edited on
Thank you. :) Yeah, sorry about that.
Topic archived. No new replies allowed.