#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With