1

I want to create a bitset with a size that I input, something like this:

int a;

int main() {
    cin >> a;
    const int l = a;
    cout << bitset<l>(123);
}

But when I run this code I receive these errors:

jdoodle.cpp:11:21: error: the value of ‘l’ is not usable in a constant expression
   11 |     cout << bitset<l>(123);
      |                     ^
jdoodle.cpp:6:11: note: ‘l’ was not initialized with a constant expression
    6 | const int l = a;
      |           ^
jdoodle.cpp:11:21: note: in template argument for type ‘long unsigned int’
   11 |     cout << bitset<l>(123);

It works fine when I set l to some integer like const int l = 6 but I get errors when I change it to const int l = a. How can I fix this?

*Edit: Thanks to those people who helped me out, I think I figured out what I need to do. I can create a bitset with a big size then I can just ignore the bits that are longer than my input.

David W
  • 158
  • 1
  • 2
  • 9
  • you can only use `std::vector` or `boost::dynamic_bitset` – phuclv Jun 29 '21 at 15:17
  • duplicate: [Define bitset size at initialization?](https://stackoverflow.com/q/3134718/995714), [Variable size bitset](https://stackoverflow.com/q/14433626/995714) – phuclv Jun 29 '21 at 15:18

1 Answers1

1

The short answer is, you can't. For std::bitset, the size needs to be determined at compile-time. See here: https://www.cplusplus.com/reference/bitset/bitset/

"The size of a bitset is fixed at compile-time (determined by its template parameter). For a class that also optimizes for space allocation and allows for dynamic resizing, see the bool specialization of vector (vector)."

Here is the link to the vector specialization: https://www.cplusplus.com/reference/vector/vector-bool/

Abstract
  • 985
  • 2
  • 8
  • 18
  • 1
    `std::vector` probably doesn't provide the string-to-binary or ???-to-binary OP expect. There's [dynamic_bitset](https://www.boost.org/doc/libs/1_76_0/libs/dynamic_bitset/dynamic_bitset.html) if he's willing to include Boost... – m88 Jun 29 '21 at 15:21