suresh m
suresh m

Reputation: 613

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';
}

How we can construct an integer value from the std::vector of bool values. I thought to convert it to a std::string and then to integer from std::vector of bool values, but converting it to string from std::vector of bool values is failing. I know that both std::vector of bool and std::string elements are not the same type. So need help for the same.

Upvotes: 3

Views: 1543

Answers (1)

lakshayg
lakshayg

Reputation: 2173

This is probably what you are looking for:

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

std::accumulate is present in the <numeric> header

Explanation: We iterate over the elements in the vector and keep accumulating the partial result in acc. When a new bit has to be added to acc, we make space for the new bit by left shifting acc and then add the bit by or'ing it with acc.

Upvotes: 8

Related Questions