如何使用C ++

时间:2018-07-07 06:35:25

标签: c++ c++11 c++14

#include <iostream>
#include <vector>

int main()
{
    std::vector<bool> bitvec{true, false, true, false, true};
    std::string str;
    for(size_t i = 0; i < bitvec.size(); ++i)
    {   
        // str += bitvec[i];
        std::vector<bool>::reference ref = bitvec[i];
        // str += ref;
        std::cout << "bitvec[" << i << "] : " << bitvec[i] << '\n';
        std::cout << "str[" << i << "] : " << str[i] << '\n';
    }   
    std::cout << "str : " << str << '\n';
}

我们如何从布尔值的std :: vector构造整数值。我想将其转换为std :: string,然后从bool值的std :: vector转换为整数,但是将其从bool值的std :: vector转换为字符串失败。我知道bool的std :: vector和std :: string元素都不是同一类型。因此需要同样的帮助。

1 个答案:

答案 0 :(得分:8)

这可能是您想要的:

auto value = std::accumulate(
    bitvec.begin(), bitvec.end(), 0ull,
    [](auto acc, auto bit) { return (acc << 1) | bit; });

std::accumulate显示在<numeric>标头中

说明:我们遍历向量中的元素,并继续在acc中累积部分结果。当必须将新位添加到acc时,我们通过向左移acc来为新位腾出空间,然后用acc或用acc将其添加。