tags:

views:

87

answers:

3

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

+2  A: 

I think if you don't know at compile time what the number of bits is going to be, you need to use vector<bool>, instead. This odd structure from the STL actually implements a bitset-like class, and not, you know, a vector of bools. Its performance is not as good as std::bitset, but the trade-off is that it can grow dynamically....

jwismar
I'd say "if you don't know at compile time what the *maximum* number of bits is going to be", since you could still use a `bitset` if you know what the maximum number of bits you can deal with is, then have another variable to track how many bits are valid.
Mike DeSimone
A: 

In that case, use std::vector<bool>.

jdv
+4  A: 

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);
Greg S