Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove vector element use the condition in vector<bool>

Tags:

c++

c++11

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.

like image 445
user1436187 Avatar asked Nov 03 '15 08:11

user1436187


1 Answers

  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

like image 76
101010 Avatar answered Sep 18 '22 02:09

101010