且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据另一个向量中的条件从向量中删除元素?

更新时间:2023-11-10 08:22:52

如果顺序无关紧要,您可以将元素交换到向量的后面,然后将其弹出.

If order doesn't matter you could swap the elements to the back of the vector and pop them.

for(size_t i=0; i<a.size();)
{
    if( !a[i].alive() )
    {
        std::swap(a[i], a.back());
        a.pop_back();
        std::swap(b[i], b.back());
        b.pop_back();
    }
    else
      ++i;
}

如果您必须保持顺序,则可以使用 std :: remove_if .请参见此答案如何获取删除谓词中被取消引用的元素的索引:

If you have to maintain the order you could use std::remove_if. See this answer how to get the index of the dereferenced element in the remove predicate:

a.erase(remove_if(begin(a), end(a),
        [b&](const myClass& d) { return b[&d - &*begin(a)].alive(); }),
        end(a));

b.erase(remove_if(begin(b), end(b), 
        [](const otherClass& d) { return d.alive(); }), 
        end(b));