Den*_*ose 12
如果您使用的是C++,std::vector<bool>则专门将元素打包到位图中.当然,如果您使用的是C++,则需要停止使用malloc.
您可以尝试查看boost :: dynamic_bitset.然后你可以做类似下面的事情(取自Boost的示例页面):
boost::dynamic_bitset<> x(100000000); // all 0's by default
x[0] = 1;
x[1] = 1;
x[4] = 1;
Run Code Online (Sandbox Code Playgroud)
bitset将为每个元素使用一个位,因此您可以在4个字节的空间中存储32个项目,从而大大减少了所需的内存量.
在C和C++中,char是最小的类型.你不能直接声明一个位数组.但是,由于任何基本类型的数组基本上都是由比特组成的,你可以模仿它们,类似这样(代码未经测试):
unsigned *array;
array = (unsigned *) malloc(100000000 / sizeof(unsigned) + 1);
/* Retrieves the value in bit i */
#define GET_BIT(array, i) (array[i / sizeof(unsigned)] & (1 << (i % sizeof(unsigned))))
/* Sets bit i to true*/
#define SET_BIT(array, i) (array[i / sizeof(unsigned)] |= (1 << (i % sizeof(unsigned))))
/* Sets bit i to false */
#define CLEAR_BIT(array, i) (array[i / sizeof(unsigned)] &= ~(1 << (i % sizeof(unsigned))))
Run Code Online (Sandbox Code Playgroud)