- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在不损失性能的情况下,编写这样的代码来循环遍历 vector ,同时从中删除不需要的元素,这是一种好的做法还是标准做法。如果有更快的方法请推荐。该 vector 的形式为 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());
}
修改后的版本
void AnimationPack::removeDeadAnimations()
{
activeAnimations.erase(std::remove_if(activeAnimations.begin(), activeAnimations.end(),
[&](AnimationState*& animation) {
if (animation->isActive())
return true;
else
return false;
}),activeAnimations.end());
}
编辑代码(根据评论建议)
void AnimationPack::removeDeadAnimations()
{
activeAnimations.erase(std::remove_if(activeAnimations.begin(), activeAnimations.end(),
[](AnimationState*& animation) { return animation->isActive(); }), activeAnimations.end());
}
最佳答案
是的,它叫做 erase-remove成语。
引自维基百科:
The erase–remove idiom is a common C++ technique to eliminate elements that fulfill a certain criterion from a C++ Standard Library container.
erase
can be used to delete an element from a collection, but for containers which are based on an array, such as vector, all elements after the deleted element have to be moved forward, to avoid "gaps" in the collection.The algorithm library provides the
remove
andremove_if
algorithms for this.These algorithms do not remove elements from the container, but move all elements that don't fit the remove criteria to the front of the range, keeping the relative order of the elements. This is done in a single pass through the data range.
remove
returns an iterator pointing to the first of these elements, so they can be deleted using a single call toerase
.
关于c++ - 遍历 vector 并删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726294/
我是一名优秀的程序员,十分优秀!