代码
第一个是位图,第二个是布隆过滤器,第三个 Twobitmap,是能表示4个状态的位图,因为普通位图一个位只能表示一个状态。
ifndef _BITMAP_H
#define _BITMAP_H
#include<vector>
#include<iostream>
#include<assert.h>
using namespace std;
class bitmap
{
public:
bitmap()
:_bitmap(((unsigned)-1 >> 3) + 1)
{}
void Set(size_t x)
{
size_t index = x/8;
size_t pos = x%8;
try
{
_bitmap.at(index)|=(1<<pos);
}
catch (const std::out_of_range& err)
std::cerr<<"Out of Range error:"<<err.what()<<endl;
}
}
void UnSet(size_t x)
{
size_t index = x/8;
size_t pos = x%8;
try
{
_bitmap.at(index)&=(~(1<<pos));
}
catch (const std::out_of_range& err)
{
std::cerr<<"Out of Range error:"<<err.what()<<endl;
}
}
bool Test(size_t x)
{
size_t index = x/8;
size_t pos = x%8;
try
try
{
return _bitmap.at(index)&(1<<pos);
}
catch (const std::out_of_range& err)
{
std::cerr<<"Out of Range error:"<<err.what()<<endl;
}
assert(false);
}
private:
std::vector<unsigned char> _bitmap;
};
class TwoBitMap
{
public:
TwoBitMap()
:_bits(((unsigned)-1 >> 3)*2 + 1)
{
}
int GetCount(size_t x)
{
int index = x / 4;
int bitpos = x % 4;
return (_bits[index] & (3 << bitpos * 2)) >> (2 * bitpos);
}
void Add(size_t x)
{
int nums = GetCount(x);
if (x < 2)
{
int index = x / 4;
int bitpos = x % 4;
_bits[index] += (1 << 2 * bitpos);
}
}
private:
vector<unsigned char>_bits;
};
template<class K,class HashFunc,class HashFunc2,class HashFunc3,class HashFunc4,class HashFunc5>
class BloomFile
{
public:
BloomFile()
:_bitmap()
{}
void Set(const K & key )
{
size_t index = HashFunc()(key);
_bitmap.Set(index);
index = HashFunc2()(key);
_bitmap.Set(index);
index = HashFunc3()(key);
_bitmap.Set(index);
index = HashFunc4()(key);
_bitmap.Set(index);
index = HashFunc5()(key);
_bitmap.Set(index);
}
bool Test(const K&key)
{
size_t index = 0;
index = HashFunc()(key);
if(!_bitmap.Test(index))
return false;
index = HashFunc2()(key);
if(!_bitmap.Test(index))
return false;
index = HashFunc3()(key);
if(!_bitmap.Test(index))
return false;
index = HashFunc4()(key);
if(!_bitmap.Test(index))
return false;
index = HashFunc5()(key);
if(!_bitmap.Test(index))
return false;
return true;
}
protected:
bitmap _bitmap;
};