码迷,mamicode.com
首页 > 编程语言 > 详细

C++实现位数组

时间:2015-08-12 16:46:52      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:位数组

当我们遇到大量整数排序时候为了节省内存空间我们可以考虑使用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;
}


版权声明:欢迎转载,如有不足之处,恳请斧正。

C++实现位数组

标签:位数组

原文地址:http://blog.csdn.net/huangshanchun/article/details/47446347

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!