user1436187 user1436187 - 1 year ago 62
C++ Question

Remove vector element use the condition in vector<bool>

I have two vectors a and b with the same size.

vector<int> a{ 4, 3, 1, 3, 1};
vector<bool> b{false,false,true,false,true};


I want to remove the element in
a
if the same element in
b
(the same index) is true.

After applying the function: a = 4,3,3

Note: I want to use
std
algorithms or functions instead of simple for loop.

Answer Source
  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());

LIVE DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download