哈希和位图都能迅速的查找元素
区别在于,哈希能查找并访问元素,但空间利用率不高
而位图仅能用来判断元素是否存在
下面是位图的实现:
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;
};原文地址:http://zhweizhi.blog.51cto.com/10800691/1784383