Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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.

like image 967
suresh m Avatar asked Jan 18 '26 11:01

suresh m


1 Answers

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.

like image 131
lakshayg Avatar answered Jan 21 '26 02:01

lakshayg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!