Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++. Accumulate binary array to integer by using custom lambda

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading