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;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值