C++ 实现布隆过滤器(BloomFilter)

代码如下:

#include 
#include 
using namespace std;

class BitMap
{
     
public:

	BitMap(size_t range) :_bit(range / 32 + 1) {
     }

	void set(const size_t num)
	{
     
		int idx = num / 32;//idx 数组下标

		int bitIdx = num % 32;

		_bit[idx] |= 1 << bitIdx;
	}

	bool find(const size_t num)
	{
     
		int idx = num / 32;
		int bitIdx = num % 32;
		return (_bit[idx] >> bitIdx) & 1;
	}

	void reset(const size_t num)
	{
     
		int idx = num / 32;
		int bitIdx = num % 32;
		_bit[idx] &= ~(1 << bitIdx);
	}


private:
	vector<int>_bit;
};

//哈希函数的个数: k = m/(n*ln(2)),其中m为位图需要的bit的大小,n为元素个数,k为哈希函数的个数

template<typename T ,typename HashFun1,typename HashFun2,typename HashFun3>
class BloomFilter
{
     
public:
	BloomFilter(const size_t num) :_bit(5 * num), _bitCount(5 * num){
     }

	void set(const T & val)
	{
     
		HashFun1 h1;
		HashFun2 h2;
		HashFun3 h3;
		int idx1 = h1(val) % _bitCount;
		int idx2 = h2(val) % _bitCount;
		int idx3 = h3(val) % _bitCount;
		_bit.set(idx1);
		_bit.set(idx2);
		_bit.set(idx3);
	}

	bool find(const T & val)
	{
     
		HashFun1 h1;
		HashFun2 h2;
		HashFun3 h3;
		int idx1 = h1(val) % _bitCount;
		int idx2 = h2(val) % _bitCount;
		int idx3 = h3(val) % _bitCount;

		if (!_bit.find(idx1)) return false;
		if (!_bit.find(idx2)) return false;
		if (!_bit.find(idx3)) return false;

		return true;//可能存在
	}

private:
	BitMap _bit;
	size_t _bitCount;
};

你可能感兴趣的:(数据结构和算法,数据结构,leetcode,C++,位图,布隆过滤器)