what's the best way to perform bitwise operations on vector<bool>
?
as i understand, vector<bool>
is a specialisation that uses one bit per boolean. I chose vector<bool>
for memory saving reasons. I know that there are some problems with vector<bool>
but for my needs it's apropriate.
now - what's the most performant way of aplying bitwise operations to whole such vectors?
if i do it in a for loop and readout each single bool and store it back, the way I understand it a lot more operations are performed inside in order to access the actual values.
thanks!
Using bitwise operations for bool helps save unnecessary branch prediction logic by the processor, resulting from a 'cmp' instruction brought in by logical operations. Replacing the logical with bitwise operations (where all operands are bool) generates more efficient code offering the same result.
The vector<bool> class is a partial specialization of vector for elements of type bool . It has an allocator for the underlying type that's used by the specialization, which provides space optimization by storing one bool value per bit.
>> Indicates the bits are to be shifted to the right. Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int .
A Bitwise And operator is represented as '&' and a logical operator is represented as '&&'. The following are some basic differences between the two operators. a) The logical and operator '&&' expects its operands to be boolean expressions (either 1 or 0) and returns a boolean value.
If the number of bits are fixed at compile time, you would be much better off using std::bitset
If not, (i.e. number of bits varies at runtime), then you should see and can use boost::dynamic_bitset
)
In both of these, it is extremely easy to do all the bitwise operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With