位图的实现

应用场景:
给40亿个不重复的无符号整数,没排过序。给一个无符号整数,如何快速判断一个数是否在这40亿个数中。

思路:如果内存够的话,40亿个整型使用位图存储需要500M左右的空间。
#include <iostream>
using namespace std; 

#include<vector>

class Bitmap
{
public:
	Bitmap()
		: _size(0)
	{}

	Bitmap(size_t size)
		:_size(0)
	{
		_array.resize((size>>5)+1);
	}

	void Set(size_t num)
	{
		size_t index = num >> 5;
		size_t i = num % 32;
		if (_array[index] & (1 << i))
		{
			return;
		}
		else
		{
			_array[index] |= (1 << i);
			_size++;
		}
	}

	void Reset(size_t num)
	{
		size_t index = num >> 5;
		size_t i = num % 32;
		if (_array[index] & (1 << i))
		{
			_array[index] &= ~(1 << i);
			_size--;
		}
		else
		{
			return;
		}
	}

	bool Test(size_t num)
	{
		size_t index = num >> 5;
		size_t i = num % 32;

		return _array[index] & (1 << i);
	}

private:
	vector<size_t> _array;
	size_t _size;
};

int main()
{
	Bitmap bt(62);
	bt.Set(1);
	bt.Set(5);

	bt.Reset(1);

	cout << bt.Test(1) << endl;
	cout << bt.Test(23) << endl;
	return 0;
}

你可能感兴趣的:(数据结构,位图)