码迷,mamicode.com
首页 > 其他好文 > 详细

位图的实现

时间:2016-05-30 15:59:45      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:public   空间   元素   

哈希和位图都能迅速的查找元素

区别在于,哈希能查找并访问元素,但空间利用率不高

而位图仅能用来判断元素是否存在

下面是位图的实现:

using namespace std;
class BitMap
{
public:
	BitMap(size_t n)
		:_size(0)
	{
		_a.resize( (n >> 5) + 1);
	}
	void Set(size_t x)
	{
		size_t index = x >> 5;
		size_t num = x % 32;
		if ((_a[index] & (1 << num)) == 0)	//不存在的话,添加并增加_size
		{
			_a[index] |= (1 << num);
			_size++;
		}
	}
	void ReSet(size_t x)
	{
		size_t index = x >> 5;
		size_t num = x % 32;
		if ((_a[index] & (1 << num)) != 0)	//存在的话,移除并减小_size
		{
			_a[index] &= ~(1 << num);
			_size--;
		}
	}
	bool Test(size_t x)
	{
		size_t index = x >> 5;
		size_t num = x % 32;
		return _a[index] & (1 << num);
	}
protected:
	vector<size_t> _a;
	size_t _size;
};


位图的实现

标签:public   空间   元素   

原文地址:http://zhweizhi.blog.51cto.com/10800691/1784383

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