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

标签 c++ c++11 vector

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

相关文章:

vector - 从旧 Vector 创建新 Vector?

opengl - LookAt函数: I'm going crazy

c++ - 初始化和设置一个 vector<int>

c++ - 如何防止需要复制传递给 avr-gcc C++ 构造函数的字符串?

c++ - 使用 [] 和 [this] 时 lambda 类型的差异

c++ - 试图对两个编译时元组整数序列求和

c++ - 是否存在在没有其他匹配障碍的情况下单独发生获取或释放障碍的情况?

java - -Djava.library.path 问题

c++ - C++ 介绍 : Concatenating strings and returning it in a function?

c++ - 为什么 gcc-4.9.2 不支持 std::string.insert(iterator, range) 返回迭代器