删除向量元素使用向量<bool>中的条件

use*_*187 6 c++ c++11

我有两个矢量a和b,大小相同.

vector<int>  a{    4,    3,   1,    3,   1};
vector<bool> b{false,false,true,false,true};
Run Code Online (Sandbox Code Playgroud)

a如果b(同一索引)中的相同元素为真,我想删除元素.

应用函数后:a = 4,3,3

注意:我想使用std算法或函数而不是简单的for循环.

101*_*010 7

  std::vector<int> v {1,2,3,4,5,6};
  std::vector<bool> b {true, false, true, false, true, false};

  v.erase(std::remove_if(v.begin(), v.end(), 
      [&b, &v](int const &i) { return b.at(&i - v.data()); }), v.end());
Run Code Online (Sandbox Code Playgroud)

现场演示


Jar*_*d42 5

void filter(std::vector<int>& v, const std::vector<bool>& b)
{
    assert(v.size() == b.size());
    auto it = b.begin();
    v.erase(std::remove_if(v.begin(), v.end(), [&](int) { return *it++; }), v.end());
}
Run Code Online (Sandbox Code Playgroud)

演示版

  • 这取决于`remove_if`将谓词按顺序应用于元素,但不能保证。 (2认同)