如何从C++中的值向量构造整数<bool>值

How to construct integer value from vector<bool> of values in C++

本文关键字:整数 gt bool lt 向量 C++      更新时间:2023-10-16
#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,然后从布尔值的 std::vector 转换为整数,但将其从布尔值的 std::vector 转换为字符串是失败的。我知道 std::vector of bool 和 std::string 元素不是同一类型。所以需要帮助。

这可能是您要查找的内容:

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

std::accumulate存在于<numeric>标头中

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