bloomfilter的实现

bloomfilter利用多个hash函数将key映射到位上,可以大幅节省存储空间。

搜索引擎的爬虫在判断自己是否爬过某个页面时就会用bloomfilter判断。

具体介绍可以看这篇博客http://www.cnblogs.com/heaad/archive/2011/01/02/1924195.html


下面是我的实现

#include "stdafx.h"
#include<cmath>
#include<iostream>
using namespace std;

class bloomfilter
{
private:
	unsigned int m;//bit数组的宽度
	unsigned int k;//使用的hash函数的个数
	double f;// False Positive的比率
	unsigned int n;//key数量
	char*bitmap;

private:
	int hash1(char*str);
	int hash2(char*str);
	int getbit(const int nn);
	void setbit(const int nn);
public:
	bloomfilter(const int N);
	bool find(char*str);
	~bloomfilter();
};

bloomfilter::bloomfilter(const int N)
{
	n = N;
	f = 0.00001;
	//要达到上述的false positive比率需要的hash函数个数为k = -ln(f) / ln(2)
	//k = -log(f) / log(2.0);
	//实际f、n、m、k有一定关系,这里偷懒了
	//n = m ln(0.6185) / ln(f)
	//m = (n + 1)*log(f) / log(0.6185);//m是bit数,一个char有8个bit
	k = 2;
	m = 1000000;
	bitmap = new char[m/8+1];
	memset(bitmap, 0, (m / 8 + 1)*sizeof(char));
}
bloomfilter::~bloomfilter()
{
	delete[]bitmap;
}
bool bloomfilter::find(char*str)
{
	int l1 = hash1(str);
	int flag = 0;
	if (getbit(l1))
		flag++;
	else
		setbit(l1);
	int l2 = hash2(str);
	if (getbit(l2))
		flag++;
	else
		setbit(l2);
	return flag == 2;
}

//位操作
int bloomfilter::getbit(const int nn)
{
	int nnn = nn >> 3;
	int lessthan8 = nn % 8;
	return (bitmap[nnn]>>lessthan8)%2==1;
}

//位操作
void bloomfilter::setbit(const int nn)
{
	int nnn = nn >>3;
	int lessthan8 = nn % 8;
	bitmap[nnn]+=(1 << lessthan8);
}

//可以自己设置合适的hash函数
int bloomfilter::hash1(char*str)
{
	unsigned int   h=0;
	char *p;
	for (p = str; *p!='\n'; p++) 
	{
		h = 31 * h + *p;
	}
	return h%m;
}

int bloomfilter::hash2(char*str)
{
	unsigned int hash = 0;
	unsigned int i = 0;
	int len = strlen(str);
	for (i = 0; i < len; str++, i++) {
		hash = (*str) + (hash << 6) + (hash << 16) - hash;
	}
	return hash%m;
}



int _tmain(int argc, _TCHAR* argv[])
{
	//cout << log(0.00001) << endl;
	//char a = 20;
	//a += 1 << 5;
	//cout << ((a >> 4)%2==1) << endl;


	bloomfilter bf(1000);
	cout<<bf.find("www.google.com");
	cout<<bf.find("www.baidu.com");
	cout<<bf.find("www.google.com");
	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值