12

What's the best way to store a bit array in C++ (no Boost, just standard containers), representing, for example, a volume allocation bitmap?

I thought std::vector<bool> was a great idea, but apparently it's Evil and deprecated, so is there a better choice?

Also:

If I have a byte array in memory, how would I go about copying them to the recommended container?
(I'm having trouble figuring this out for vector<bool>.)

4

6 回答 6

2

一个 char 数组,然后用 0x1 屏蔽将充当一个位数组。

例子:

char bitarray[4]; // since 4*8 this array actually contains 32 bits

char getBit(int index) {
    return (bitarray[index/8] >> 7-(index & 0x7)) & 0x1;
}

void setBit(int index, int value) {
    bitarray[index/8] = bitarray[index/8] | (value & 0x1) << 7-(index & 0x7);
}

当然,这些操作通常相对较慢,但如果内存是一个问题,这是一个不错的方法。我为此选择了 char 以减少所需的班次数量。但是,使用整数可能仍然更快。

于 2011-10-20T00:46:45.210 回答
2

对于普通 C++,有std::bitset。

Bitset 与 vector(也称为 bit_vector)非常相似:它包含一组位,并提供对每个位的恒定时间访问。bitset 和 vector 之间有两个主要区别。首先,bitset 的大小不能改变:bitset 的模板参数 N,它指定了 bitset 中的位数,必须是一个整数常量。其次,bitset 不是一个序列;事实上,它根本不是一个 STL Container。

Matt Austern 有一篇很好的文章介绍了它的使用。

另外:如果您的字节数组(位数组?)适合无符号长,那么您可以将其分配给 std::bitset 直接:

unsigned long myByteArray = 0xABCD;
std::bitset<32> bitten( myByteArray );
于 2011-10-20T00:54:58.663 回答
2

仅在 6 年后为后代发布此内容:就像其中一位评论者所说,我得出的结论是,将其用作自己的专业类型是完全可以的。std::vector<bool>您唯一需要注意的是不要将其视为标准bool容器,因为它不是。

于 2017-05-16T10:23:07.390 回答
1

只要您的位数组具有固定大小, std::bitset 就可以
附带说明一下,还有 std::dynamic_bitset,但我不能 100% 确定它是否已成为标准。

于 2011-10-20T00:53:10.127 回答
0

I think some of the points made on the site you linked to are not correct by the way. On almost every computer the size of a bit is really one byte (same as a character) because computers can only address a byte not a bit within a byte (if you could then you would only have one eighth of the addressing space you currently have with bytes)

I would just use a byte for your vector because it gives other people who read your code a better idea of the memory footprint of your application.

Ram is very plentiful in modern computers so you may be able to use larger integral types but realistically you can't go smaller than a byte.

To copy data from one container to another first create an iterator for the container

vector::iterator myItr = myVector.begin()

and iterate through the vector with a while loop or a for loop until myItr reaches myVector.end().

For example

for(vector<bool>::iterator myItr = myVector.begin(); myItr<myVector.end(); ++myItr)
{
   otherContainer.append(*myItr);
}
于 2011-10-20T00:41:45.103 回答
0

强大的 C/С++ 位数组库:https ://github.com/noporpoise/BitArray

于 2019-03-05T15:57:23.897 回答