0

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++?

user1850980
  • 991
  • 1
  • 10
  • 15

2 Answers2

1

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.

keyser
  • 18,829
  • 16
  • 59
  • 101
  • Indeed, I think I have to use a dynamic size solution, because I also return bitsets from functions, so I would need to know the size for the function definition as well. Thanks, I'll try the suggested Alternatives. – user1850980 Apr 27 '14 at 10:20
0

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

jaybny
  • 1,026
  • 2
  • 13
  • 29