Looking for a more automatic way for objects to call functions

Started by
2 comments, last by Wavesonics 16 years, 1 month ago
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!
Advertisement
Arrays.
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.
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++ :)
==============================
A Developers Blog | Dark Rock Studios - My Site

This topic is closed to new replies.

Advertisement