如何从C++中的值向量构造整数<bool>值
How to construct integer value from vector<bool> of values in C++
#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 或添加位。
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一