bitwise operations on vector<bool>

只愿长相守 提交于 2019-11-30 08:55:38

问题


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!


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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>());


来源:https://stackoverflow.com/questions/4048749/bitwise-operations-on-vectorbool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!