bit_vector的实现(类似于标准库中的bitset的功能)

#pragma once
#include 

using namespace std;

class bit_vector
{
public:
	bit_vector(int);
	~bit_vector(void);
	int get_bit(int);
	void set_bit(int);
	void clear_bit(int);
	void reverse_bit(int);
	string to_string();
private:
	unsigned int * ar;
	int len;
	int get_bit(unsigned int, int);
	int set_bit(unsigned int, int);
	int clear_bit(unsigned int, int);
	int reverse_bit(unsigned int, int);
};


#include "bit_vector.h"
#include 
#include 

using namespace std;

// 构造函数
bit_vector::bit_vector(int len)
{
	this->len = len;
	int alen = len % 32 == 0 ? len / 32 : len / 32 + 1;
	ar = new unsigned int[alen];
	for (int i = 0; i < alen; i++)
		ar[i] = 0;
}

// 析构函数
bit_vector::~bit_vector(void)
{
	if (ar != NULL)
		delete [] ar;
}

// 获取一位
int bit_vector::get_bit(int i)
{
	assert(i >= 0 && i < len);
	int alen = i / 32;
	int blen = i % 32;
	return get_bit(ar[alen], blen);
}

// 取反一位
void bit_vector::reverse_bit(int i)
{
	assert(i >= 0 && i < len);
	int alen = i / 32;
	int blen = i % 32;
	ar[alen] = reverse_bit(ar[alen], blen);
}

// 设置一位,把该位设置为1
void bit_vector::set_bit(int i)
{
	assert(i >= 0 && i < len);
	int alen = i / 32;
	int blen = i % 32;
	ar[alen] = set_bit(ar[alen], blen);
}

// 清除一位,把该位设置为0
void bit_vector::clear_bit(int i)
{
	assert(i >= 0 && i < len);
	int alen = i / 32;
	int blen = i % 32;
	ar[alen] = clear_bit(ar[alen], blen);
}


// 获取一个int的某一位,从0开始
int bit_vector::get_bit(unsigned int value, int index)
{
	assert(index >= 0 && index < 32);
	return (value >> index) & 1;
}

// 设置某位为1
int bit_vector::set_bit(unsigned int value, int index)
{
	assert(index >= 0 && index < 32);
	return value | (1 << index);
}

// 设置某位为0
int bit_vector::clear_bit(unsigned int value, int index)
{
	assert(index >= 0 && index < 32);
	return value & ~(1 << index);
}

// 取反某一位
int bit_vector::reverse_bit(unsigned int value, int index)
{
	assert(index >= 0 && index < 32);
	return value ^ (1<
#include 
#include "bit_vector.h"

using namespace std;

int main()
{
	bit_vector bv(100);
	cout<

posted on 2010-07-29 12:44  小橋流水  阅读(425)  评论(0编辑  收藏  举报

导航