vector::erase Questions

Hello,

It appears that the vector::erase method isn't working for me. I have a main play() function for this simulation that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void BunnyGraduation::play()
{
	// Count each year that progresses
	int yearsAlive = 0;

	init(); // Initialize the colony with 5 bunnies
	printColony(); // Print the initial colony

	while (!gameOver()) // While game is not over. . .
	{
		printColony(); // Print the colony
		breed(); // Breed the bunnies
		infect(); // Infect bunnies.
		starving(); // Determine if the new colony is starving because of births
		ageColony(); // Age the colony
		yearsAlive++; // Increment years alive
	}
	// When loop ends, print how many years they're alive
	cout << "Years survived: " << yearsAlive << endl;

}


In the "starving" method - it checks if the colony size is >= 1000 and is supposed to kill half of the colony, chosen randomly. Starving method looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void BunnyGraduation::starving()
{
	if (colony.size() >= 1000) // If the colony is greater than 1000 bunnies
	{
		int randomNumber = 0;
		// Output that they're starving
		cout << "\nThe colony is starving! Colony size: " << colony.size() << endl;

		for (int i = 0; i < colony.size() / 2; i++) // While i is less than half of the colony size
		{
			randomNumber = rand() % colony.size();
			kill(randomNumber); // kill a random bunny
		}
	}
}


and the "Kill()" function looks like this:

1
2
3
4
5
6
7
void BunnyGraduation::kill( int suppliedIndex )
{
	// Output that a bunny has died.
	//cout << endl << colony.at(suppliedIndex).getName() << " died!" << endl;
	// Erase that bunny from the vector
	colony.erase(colony.begin() + suppliedIndex);
}


But for some reason, half the colony is not being killed properly when the starving function is called because the colony size keeps getting exponentially larger.
Or to remove just one element (without preserving the original order):

1
2
3
4
5
6
7
8
void BunnyGraduation::kill( int suppliedIndex )
{
	// Output that a bunny has died.
	//cout << endl << colony.at(suppliedIndex).getName() << " died!" << endl;
	// Erase that bunny from the vector
        std::swap( colony[suppliedIndex], colony.back() ) ;
	colony.pop_back() ;
}


Each time a bunny is killed, the size() decreases. The loop should probably be:
1
2
3
const auto original_size =  colony.size() ;
for (int i = 0; i < original_size / 2; ++i )
    kill( rand() % colony.size() ); // kill a random bunny 


Or simpler:
1
2
std::random_shuffle( colony.begin(), colony.end() ) ;
colony.resize( colony.size() / 2 ) ;

1
2
std::random_shuffle( colony.begin(), colony.end() ) ;
colony.resize( colony.size() / 2 ) ;


I like this. Thank you :)
Topic archived. No new replies allowed.