C++实现位数组

当我们遇到大量整数排序时候为了节省内存空间我们能够考虑使用bit数组来实现,缺点是其仅仅适用于正整数。

思想:

在32位系统一个int类型占4个字节,按位来计算一个int类型能够记录32个数。因此,採用int型数组和移位来实现相关功能。

C++实现bit数组

#include<iostream>
using namespace std;
const unsigned int bitValue[32]=
{
	0x80000000,
	0x40000000,
	0x20000000,
	0x10000000,
	0x08000000,
	0x04000000,
	0x02000000,
	0x01000000,
	0x00800000,
	0x00400000,
	0x00200000,
	0x00100000,
	0x00080000,
	0x00040000,
	0x00020000,
	0x00010000,
	0x00008000,
	0x00004000,
	0x00002000,
	0x00001000,
	0x00000800,
	0x00000400,
	0x00000200,
	0x00000100,
	0x00000080,
	0x00000040,
	0x00000020,
	0x00000010,
	0x00000008,
	0x00000004,
	0x00000002,
	0x00000001
};
const int bitLen =sizeof(int)*8;
class BitArray
{
private:
	unsigned int len;
	unsigned int *bit;
public:
	BitArray(unsigned int length)
	{
		if(length<0)
		{
			throw "length 小于 0";
		}
		this->len=length;
		bit= new unsigned int[length/bitLen+(length%bitLen>0?1:0)]();//初始化为0
	}
	unsigned int getBit(int index)
	{
		if(index<0||index>len)
		{
			throw "index 越界";
		}
		unsigned int data=bit[index/bitLen];
		return (data&bitValue[index%bitLen])>>(bitLen-index%bitLen-1);
	}
	void setBit(unsigned int index,unsigned int value)
	{
		if(index<0||index>len)
		{
			throw "index 越界";
		}
		if(value!=1&&value!=0)
		{
			throw "value 值仅仅能为1或者0";
		}
		unsigned int data=bit[index/bitLen];//计算出其属于数组中哪个int值
		if(value==1)
		{
			bit[index/bitLen]=data|bitValue[index%bitLen];
		}else
		{
			bit[index/bitLen]=data&~bitValue[index%bitLen];
		}
	}
	unsigned int getLength()
	{
		return this->len;
	}
	~BitArray()
	{
		delete[] bit;
	}
};

int main()
{
	try
	{
		BitArray bArray(1000000);
		bArray.setBit(99999,1);
		bArray.setBit(201,1);

		cout<<bArray.getBit(0)<<endl;
		cout<<bArray.getBit(99999)<<endl;
		cout<<bArray.getBit(10000)<<endl;
	}
	catch(char *str_ex)
	{
		cout<<str_ex<<endl;
	}
	cin.get();
	return 0;
}


原文地址:https://www.cnblogs.com/wzjhoutai/p/7082388.html