gpt4 book ai didi

c++ - 遍历 vector 并删除内容

转载 作者:行者123 更新时间:2023-11-27 23:55:15 27 4
gpt4 key购买 nike

在不损失性能的情况下,编写这样的代码来循环遍历 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 and remove_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 to erase.

关于c++ - 遍历 vector 并删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726294/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com