Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable size bitset [duplicate]

I am practicing a question on array in which I have to find unique elements. Now for this my logic is to find the max element in the array and define the bitset for that. But problem is bitset needs a constant value so how to overcome this, below are some of my question on this:

a) Can I, by any chance, define the bitset with a variable size?
b) If not, then what is the best approach to use vector<bool> or vector<char>?
c) I know boost has a dynamic bitset but as I am doing this for learning I want to know of alternate approaches.

like image 351
JackSparrow Avatar asked Jan 21 '13 06:01

JackSparrow


People also ask

How do you change the size of a Bitset?

Java BitSet size() method The maximum element in the set is the size - 1st element. The default size of the bit set is 64-bit space. If the bit is set at index larger than the current BitSet size, it increases its bit space in the multiplication of 64*n, where n starts from 1, 2, 3, so on.

How do you define the size of a Bitset in C++?

bitset::size() is a built-in STL in C++ which returns the total number of bits. Parameter: The function accepts no parameter. Return Value: The function returns an integral value which signifies the number of bits. It eventually returns the size that has been given while initializing the bitset.

Is Bitset faster than vector bool?

So it seems under these conditions, bitset is faster than vector when the code is optimized, while vector actually comes out on top by a (very) small margin when it's not.

How much memory does Bitset use?

Typically on a 32-bit processor, the compiler will make the allocated memory size a multiple of 4 bytes, and so the nearest multiple of 4 greater than 3/8 is 4 bytes.


1 Answers

The std::bitset<N> template requires a fixed size in advance. The std::vector<bool> is the C++ standard's way of providing a variable-length bitvector, and it offers functionality similar to a bitset that can grow and shrink.

As for whether it's better or worse to use vector<char> or vector<bool>: the vector<bool> is a much more direct way of accomplishing this goal. I would start off by using it, then switch to vector<char> if the performance is unacceptable. In general, it's good to try to write the cleanest, most straightforward implementation first, then to optimize later on.

Hope this helps!

like image 137
templatetypedef Avatar answered Oct 02 '22 20:10

templatetypedef