Question

I need a global variable in my C++ program. It is going to be a vector of bitsets. However, the size of the bitsets is determined at runtime by a function.

So basically, I would like to register the variable (in the top part of my code) and later define it properly by the function that determines the bitarrays' size.

Is there a way to do this in C++?

Was it helpful?

Solution

One way would be to use dynamic_bitset from boost:

#include <iostream>
#include <vector>
#include <boost/dynamic_bitset.hpp>

std::vector< boost::dynamic_bitset<> > bitsets;

int main() {
    bitsets.push_back(boost::dynamic_bitset<>(1024));
    bitsets.push_back(boost::dynamic_bitset<>(2048));
    std::cout << bitsets[0].size() << std::endl;
    std::cout << bitsets[1].size() << std::endl;
}

You could also use a vector<bool> instead, i.e. vector< vector<bool> > for a vector of bitsets. It is specialized to only use one bit per element.

OTHER TIPS

bitsets sizes are fixed at compile time. just use static vector<vector<bool>> MyGlobalBits;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top