【问题标题】:How to construct integer value from vector<bool> of values in C++如何从 C++ 中值的向量<bool> 构造整数值
【发布时间】:2018-07-07 06:35:24
【问题描述】:
#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';
}

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

【问题讨论】:

  • std::vector&lt;bool&gt; 不是一个好主意,而是使用std::bitset
  • 你能举一个输入向量和预期输出的int值的例子吗?
  • 您在寻找什么样的转换?您想将布尔值解释为位吗?如果是,那么哪个位置代表最高有效位,第一个还是最后一个。
  • 我希望将各个位表示为二进制数字,然后将其转换为整数(十进制)值。
  • 哪个位置代表最高有效位?

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


【解决方案1】:

这可能是您正在寻找的:

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

std::accumulate 出现在 &lt;numeric&gt; 标头中

解释:我们遍历向量中的元素,并在acc 中不断累积部分结果。当必须向acc 添加一个新位时,我们通过左移acc 为新位腾出空间,然后使用 acc 进行或运算来添加该位。

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 2013-07-21
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2012-03-14
    • 2021-04-03
    相关资源
    最近更新 更多