# Looking for a more automatic way for objects to call functions

This topic is 3607 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a list of missiles, mis1 to mis 20, and I'm tired of coding missile1.whatever = annother_whatever missile2.whatever = annother_whatever ... missile20.whatever = annother_whatever Is there a way to put this into a few lines? Is it even a good way? When the missiles die, missileactive = false; and it is not drawn until it is needed. I am looking for a better way to do this too. :) And finally, I would like to know what this is called, so that I may tell all my friends. Thank you!

Arrays.

##### Share on other sites
Create a vector which contains the active missiles.
#include <vector>typedef std::vector<Missile> Missiles;Missiles missiles;

When a new missile is created, add it to the vector:
Missile added(constructor_args);missiles.push_back(added);

This will have the vector store a copy of the missile. To perform a given operation on all missiles, define a function which performs that operation and apply it to the entire vector:
#include <algorithm>void update(Missile &m) { m.whatever = another_whatever; }std::for_each(missiles.begin(), missiles.end(), &update);

To detect which missiles are dead and remove them from the vector, define an is-dead function and use remove-if:
bool is_dead(const Missile &m) { return ! m.active; }missiles.erase( std::remove_if( missiles.begin(), missiles.end(), &is_dead ),                missiles.end() );

This moves all dead missiles to the end of the vector and then removes them in one sweep, thus guaranteeing that only live missiles are in the vector.