question about bitset in c++ [duplicate]
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
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);
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....
In that case, use std::vector<bool>
.
精彩评论