代码
第一个是位图,第二个是布隆过滤器,第三个 Twobitmap,是能表示4个状态的位图,因为普通位图一个位只能表示一个状态。
ifndef _BITMAP_H
#define _BITMAP_H
#include<vector>
#include<iostream>
#include<assert.h>
using namespace std;
class bitmap
{
public:
bitmap()
:_bitmap(((unsigned)- >> ) + )
{}
void Set(size_t x)
{
size_t index = x/;
size_t pos = x%;
try
{
_bitmap.at(index)|=(<<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/;
size_t pos = x%;
try
{
_bitmap.at(index)&=(~(<<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/;
size_t pos = x%;
try
try
{
return _bitmap.at(index)&(<<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)- >> )* + )
{
}
int GetCount(size_t x)
{
int index = x / ;
int bitpos = x % ;
return (_bits[index] & ( << bitpos * )) >> ( * bitpos);
}
void Add(size_t x)
{
int nums = GetCount(x);
if (x < )
{
int index = x / ;
int bitpos = x % ;
_bits[index] += ( << * 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 = ;
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;
};