如何制作 'bit' 数组而不是 'int' 数组?
How do I make 'bit' array instead of 'int' array?
通常,在 C++ 中,在创建数组时,我将其声明为 int。
但是,由于我只处理二进制数(仅 1 和 0),我认为我可以将 4 个字节 'int' 转换为 1 位。
例如
int array1[] = {1,0,0,0,0,1,0}; // -----had total of 32 bytes
因为它只是二进制,内存效率仅为 1/32,因为每个 int 1 将存储为 000000000000000000000000000001
(4 字节)。
所以我的问题是如何将所有这些转换成位,以便 32 字节可以 'compressed' 变成 1 字节(而不是 32 字节的 8 int,我想要 8 位数据)?
使用std::bitset。我想这就是你想要的。
我不知道你是不是一个有竞争力的程序员,但有时在竞争性编程中需要有 10^9 个标志。那么bitset
或者在sieve的素数测定中这个非常有帮助。
#include<bitset>
...
...
bitset<10000000> bs;
..
bs[1]=1;
bs[i]=0;
..etc
Conventionally, in C++, upon creating an array, I declare it as an int.
没有这样的共同约定。
However, since I am only dealing with binary numbers (1 and 0 only), I am thinking that is that possible for me to covert the 4 bytes 'int' to 1 bit.
很自然地,人们可能会认为这应该导致声明类似
的内容
bool array1[]{true,false,false,false,false,true,false};
虽然上面的实现只是将一个位的space减少为unsigned char
,这是c++中可以寻址的最小内存单元
幸运的是,c++ 提供了 std::vector<bool>
的专门化,实际上 space 可以根据需要优化您的位数组。
通常,在 C++ 中,在创建数组时,我将其声明为 int。 但是,由于我只处理二进制数(仅 1 和 0),我认为我可以将 4 个字节 'int' 转换为 1 位。
例如
int array1[] = {1,0,0,0,0,1,0}; // -----had total of 32 bytes
因为它只是二进制,内存效率仅为 1/32,因为每个 int 1 将存储为 000000000000000000000000000001
(4 字节)。
所以我的问题是如何将所有这些转换成位,以便 32 字节可以 'compressed' 变成 1 字节(而不是 32 字节的 8 int,我想要 8 位数据)?
使用std::bitset。我想这就是你想要的。
我不知道你是不是一个有竞争力的程序员,但有时在竞争性编程中需要有 10^9 个标志。那么bitset
或者在sieve的素数测定中这个非常有帮助。
#include<bitset>
...
...
bitset<10000000> bs;
..
bs[1]=1;
bs[i]=0;
..etc
Conventionally, in C++, upon creating an array, I declare it as an int.
没有这样的共同约定。
However, since I am only dealing with binary numbers (1 and 0 only), I am thinking that is that possible for me to covert the 4 bytes 'int' to 1 bit.
很自然地,人们可能会认为这应该导致声明类似
的内容bool array1[]{true,false,false,false,false,true,false};
虽然上面的实现只是将一个位的space减少为unsigned char
,这是c++中可以寻址的最小内存单元
幸运的是,c++ 提供了 std::vector<bool>
的专门化,实际上 space 可以根据需要优化您的位数组。