How can I accumulate a binary array containing 0 and 1 into an integer?
vector<int> arr = {1,0,1,0,1,1,1,0,1,0,0};
int num = accumulate(
arr.begin(), arr.end(),
[](int &a, int &b)
{
// ???
}
);
At each step I need something like this:
if(arr[i] % 2) num += pow(2, i);
But how to implement this in lambda? How to get i in lambda?
>Solution :
If you must use a position, you can capture an index variable by reference in your lambda. Of course, the usual caveats about pow and floating point numbers apply, and this is unnecessary to accomplish the task, but it is possible.
int idx = 0;
int number = std::accumulate(
arr.begin(), arr.end(),
[&idx](const int num, const int bit) {
return num + bit * std::pow(2, idx++);
}
);
Sidenote: arr is a misleading name for a std::vector variable.
Keep in mind also that the lambda you pass to std::accumulate should not mutate either of its two arguments, but rather just generate a new value.