So I have a vector:
vector<Enemy*> enemies;
This vector hold enemies, which are created dynamically throughout the game.
if(rand() % 1000 > 998)
{
Enemy * enemy = new Enemy(num_of_enemies);
enemies.push_back(enemy);
}
The problem with this being is that the vector is ever growing even if the enemy has been deleted, which is slowing down my game.
Essentially I want to move the contents of the vector to a new one, but only the elements that actually hold an enemy.
I read that there was something called std::move
but I'm not really sure how to implement it properly, or if it will successfully move the elements that contain enemies, and not just the whole vector.
Any help with code implementation of structuring would be greatly appreciated.
Here’s a complete workflow of how to handle spawning and despawning enemies. Note that there are no pointers at all involved.
Spawning an enemy:
if (if random_float_between_0_and_1() < 0.002)
enemies.push_back(Enemy{arguments});
Despawning enemies; according to your comment below, should look something like this:
auto last_iter = std::remove_if(enemies.begin(), enemies.end(), is_dead);
enemies.erase(last_iter, enemies.end());
Here, is_dead
is a function that takes an Enemy const&
and determines whether it collided with a player or the screen bounds:
bool is_dead(Enemy const& enemy) {
return outside_screen_area(enemy) or near_player(enemy);
}
The functions outside_screen_area
and near_player
should be straightforward for you to implement.
To understand how the code above works, consult the documentations of std::remove
and std::vector::erase
.
Another thing: implement the function random_float_between_0_and_1
in terms of the standard library random library that ships with C++11. Don’t use std::rand
or modulo operations on integer random numbers, they work badly (i.e. they’re not truly uniformly distributed and will give skewed results).