Is this a good or standard practice to code like this to loop through a vector while deleting unwanted elements from it without losing performance. If there is a faster way please suggest it. This vector is of the form std::vector<AnimationState*> activeAnimations;
void AnimationPack::removeDeadAnimations() { int counter = 0; std::remove_if(activeAnimations.begin(), activeAnimations.end(), [&](AnimationState*& animation) { if (animation->isActive()) { counter++; return true; } else return false; }); activeAnimations.erase(activeAnimations.end() - counter, activeAnimations.end()); } Edited version
void AnimationPack::removeDeadAnimations() { activeAnimations.erase(std::remove_if(activeAnimations.begin(), activeAnimations.end(), [&](AnimationState*& animation) { if (animation->isActive()) return true; else return false; }),activeAnimations.end()); } Edited Code (As suggested from comments)
void AnimationPack::removeDeadAnimations() { activeAnimations.erase(std::remove_if(activeAnimations.begin(), activeAnimations.end(), [](AnimationState*& animation) { return animation->isActive(); }), activeAnimations.end()); }
auto it = std::remove_if(v.begin(), v.end(), ...); v.erase(it, v.end());is pretty well idiomatic – it's hard to answer without knowing what you find scary about it.remove_ifand whatever else they find confusing, this is very common.return animation->isActive();.activeAnimationscontains owning pointers you must remember todeletethem yourself. If that's the case, consider usingstd::vector<std::unique_ptr<AnimationState>>orstd::vector<AnimationState>instead.