在C位阵列++ [英] Bit Array in C++
问题描述
在与项目欧拉问题,我的工作经常需要大(> 10 ** 7)位阵列。
When working with Project Euler problems I often need large (> 10**7) bit array's.
我的正常的做法是之一:
My normal approach is one of:
bool* sieve = new bool[N];
bool sieve[N];
当N = 1,000,000我的程序使用1兆字节(8 * 1,000,000比特)。
When N = 1,000,000 my program uses 1 MegaByte (8 * 1,000,000 bits).
有没有使用比BOOL存储阵列位在C中更有效的方式++?
Is there a more efficient way to use store bit arrays than bool in c++?
推荐答案
使用的 和std :: bitset
(如 N
是一个常数)以其他方式使用的std ::矢量<&布尔GT;
如其他人所说的(但不要忘记阅读这个优秀的文章香草萨特的)
Use std::bitset
(if N
is a constant) otherwise use std::vector<bool>
as others have mentioned (but dont forget reading this excellent article by Herb Sutter)
一个bitset是设计用来存储位一个特殊的容器类。(只有两个可能值的元素:0或1,真或假,...)
A bitset is a special container class that is designed to store bits (elements with only two possible values: 0 or 1, true or false, ...).
类非常相似的规则阵列,的但优化空间分配强>:每个元素只占用一个位(这是比在C ++中的最小元素种类较少八倍:炭)。
The class is very similar to a regular array, but optimizing for space allocation: each element occupies only one bit (which is eight times less than the smallest elemental type in C++: char).
修改
香草萨特(该文章中)提到
Herb Sutter (in that article) mentions that
原因的std ::矢量&lt;布尔>是不合格的是,它拉在幕后花招,企图以优化空间:而不是存储一个完整的char或int对于每一个BOOL [1](占用至少8倍的空间,平台上有8位字符)的它包的布尔变量并将它们存储为单个位的(在里面,比如说,字符)在其内部重新presentation。
The reason std::vector< bool > is nonconforming is that it pulls tricks under the covers in an attempt to optimize for space: Instead of storing a full char or int for every bool[1] (taking up at least 8 times the space, on platforms with 8-bit chars), it packs the bools and stores them as individual bits(inside, say, chars) in its internal representation.
的std ::矢量&lt;布尔> 力量由标准供奉它的所有用户特定的优化。这不是一个好主意;不同的用户有不同的需求,现在矢量的所有用户必须支付的性能损失,即使他们不想要或需要节省的空间。
std::vector < bool > forces a specific optimization on all users by enshrining it in the standard. That's not a good idea; different users have different requirements, and now all users of vector must pay the performance penalty even if they don't want or need the space savings.
编辑2
如果你已经使用升压可以使用 的boost ::来,dynamic_bitset
(如 N
在运行时是已知的)
And if you have used Boost you can use boost::dynamic_bitset
(if N
is known at runtime)
这篇关于在C位阵列++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!