Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise operations on vector<bool>

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!

like image 451
Mat Avatar asked Oct 29 '10 03:10

Mat


People also ask

Can you use bitwise operators on Booleans?

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.

What is a bool vector?

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.

What is >> in bitwise?

>> 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 .

Is && A bitwise operator?

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.


1 Answers

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.

like image 156
Arun Avatar answered Sep 20 '22 07:09

Arun