Sign in to follow this  

Looking for a more automatic way for objects to call functions

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!

Share this post

Link to post
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);

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 !; }
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.

Share this post

Link to post
Share on other sites
Man, I've never looked into the STL algorithm include, std::for_each, std::remove_if, good stuff!

Always, always learning new things about C++ :)

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this