3
#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.

8
  • 3
    std::vector<bool> isn't such a good idea, rather use a std::bitset. Commented Jul 7, 2018 at 6:36
  • Can you give an example of the input vector and the int value expected as output. Commented Jul 7, 2018 at 6:38
  • What kind of conversion are you looking for? Do you want to interpret the booleans as bits? If so, then which position represents the most significant bit, first or last. Commented Jul 7, 2018 at 6:39
  • I want individual bits to be represented as binary digits and then it be converted to integer(decimal) value. Commented Jul 7, 2018 at 6:40
  • 1
    Which position represents the most significant bit? Commented Jul 7, 2018 at 6:41

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.