jsomers89 jsomers89 - 2 months ago 9
C++ Question

Fill a vector using a lambda to determine if the index is even or odd

I am attempting to write a lambda statement that will fill a vector of type bool depending on if the index is even or odd and it is all coming out false.

vector<bool> v(6);
bool start = false;
generate(v.begin(), v.end(), [&start]()->bool {return start % 2 == 0; });

Answer

Will this do for your needs?

vector<bool> v(6);
bool start = false;
generate(
  v.begin(), v.end(), 
  [&start]()->bool {bool ret=start; start =!start; return ret; }
);

Or this

vector<bool> v(6);
int start = 0;
generate(
  v.begin(), v.end(), 
  [&start]()->bool {return start++ % 2; }
);