I often collect some data in a class to prevent public / global access errors and provide some common methods on it, for example:
class GameArea{ std::vector<Enemy*> enemies; std::wstring name; public: void makeAllEnemiesScared(); Enemy * getEnemy(unsigned index); };
GameArea is just a simplified example here. This will be a kind of custom container / menager with some specialized methods (but it's not just a container).
The ideal situation is when I know what operations will be performed on each Enemy once, and they occur in several places, so I can declare them directly in GameArea (for example, makeAllEnemiesScared() ).
Other times I can go with:
for(unsigned i=0; i<gameArea->getEnemiesCount(); i++){ Enemy * enemy = gameArea->getEnemy(i); ... }
But it has some disadvantages :
- I can't use C ++ 11 clean & nice
for(auto &Enemy : enemies) loop, - This is inefficient (so many calls to
getEnemy(index) ) - This is not the goal for
getEnemy(index) to iterate over all elements - this is useful in the case when we want to select one or more of them, it also has a check on index < enemies.size() inside - it is terrible to check it on every element in cycle.
NOTE: I think of cases when I do something very special ( you should not create a divided method in GameArea , but for each element > of GameArea::enemies ).
I was thinking of some kind of GameArea::onEachEnemy(... function ...) method that takes function as a parameter (or maybe a better lambda?). This is a good decision?
Or maybe a different approach should be used? Like returning std::vector from GameArea - which looks a bit ugly to me. I do not want the user to think that he can actually add or remove elements to / from this vector directly.
source share