C++。使用自定义 lambda 将二进制数组累加为整数

问题描述 投票:0回答:2

如何将包含 0 和 1 的二进制数组累加为整数?

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)
    { // ???  });

在每一步我都需要这样的东西:

if(i % 2) num += pow(i, 2);

但是如何在 lambda 中实现这一点呢?如何在 lambda 中得到

i

c++ c++11 lambda stl
2个回答
0
投票

如果您的意思是

i
是一个 intex,则不需要这里。事实上,使用
std::accumulate
通过位运算进行二进制到十进制的转换要容易得多。

const int num = std::accumulate(arr.begin(), arr.end(), 0, [&](int num, int bit)
{
    // Update num based on the position of the bit
    num = (num << 1) | bit;
    return num;
});

0
投票

我的猜测是,您正在寻找

std::accumulate(arr.begin(), arr.end(), 0,
  [](int acc, int val) { return acc * 2 + val; })

// Note reverse iterators
std::accumulate(arr.rbegin(), arr.rend(), 0,
  [](int acc, int val) { return acc * 2 + val; })

取决于

arr
是否应该从最低有效位到最高有效位排序,反之亦然。

© www.soinside.com 2019 - 2024. All rights reserved.