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 performe开发者_如何学God inside in order to access the actual values.
thanks!
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.
Ignoring the title of your question, lets answer this question, instead:
what's the best way to perform bitwise operations on vector?
The best way is to define your vector as vector<unsigned char>
(or vector<uint32_t>
, or whichever other integer type you choose), and do your bitwise operations how you normally would for an array of unsigned integers. Things will be much faster this way, and there will be no hidden mechanism.
You can use division (or bitwise operators, if you're slick) to resolve which array index you need to operate against, and for-loops to apply bitwise operations larger than a single element.
Here's a related question: Bit twiddling a lot of bits in C
You will basically be doing these same operations, if and when you decide to wrap vector<unsigned some-int-type>
with your own operators.
I read both these answers, but just wanted a quick solution, and implemented something horrible.
You can make the bitwise operators work on vector<bool>
, but the code has to be specialized for the c++ standard library implementation or fall back to the slow form. Here's my operator|
for GNU libstdc++-v3:
std::vector<bool> operator|(std::vector<bool> A, const std::vector<bool>& B)
{
if (A.size() != B.size())
throw std::invalid_argument("differently sized bitwise operands");
std::vector<bool>::iterator itA = A.begin();
std::vector<bool>::const_iterator itB = B.begin();
// c++ implementation-specific
while (itA < A.end())
*(itA._M_p ++) |= *(itB._M_p ++); // word-at-a-time bitwise operation
return A;
}
This is of course pretty bad. Somebody updates GCC, the new version stores things differently, and your code breaks for no apparent reason.
This one should work too.
std::vector<bool> v3(v1.size());
std::transform(v1.begin(), v1.end(),
v2.begin(), v3.begin(), std::logical_and<bool>());
精彩评论