Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about bitset in c++ [duplicate]

Tags:

c++

stl

bitset

i have tried to implement following code

#include <iostream>
#include <bitset>

using namespace std;
int main(){
    //bitset<4>mybits;
    //cout<<mybits<<endl;
    int a[]={3,1,4,5,7,8};
    int max=a[0];
     int t=sizeof(a)/sizeof(a[0]);
       for (int i=1;i<t;i++){
             if (a[i]>max){
                 max=a[i];
             }
       }

       bitset<max+1>mybits;







     return 0;
}

but it says that max must have constant value what to do?here i know that maximum element is eight but imagine that we enter numbers from keyboard in this case maximum number is unknown thanks


1 Answers

The problem: the size of a C++ bitset has to be known at compile-time, and therefore the size is the template parameter to the bitset.

A possible solution (and probably better than using a std::vector<bool>, as suggested by other posters): if you wanted to use a bitset whose size you can fix at runtime, you can use dynamic_bitset from the Boost library.

In your case, you would construct it with

boost::dynamic_bitset<> mybits(max+1);
like image 52
Greg S Avatar answered May 04 '26 05:05

Greg S