布隆过滤器
布隆过滤器(Bloom Filter)是1970年由布隆提出的。它实际上是一个很长的二进制向量和一系列随机映射函数。布隆过滤器可以用于检索一个元素是否在一个集合中。它的优点是空间效率和查询时间都远远超过一般的算法,缺点是有一定的误识别率和删除困难。
简单来说,布隆过滤器就是基于位图来实现的。确定某个元素是否出现在一个范围内。比如说一个字符串,无法用一个位来表示是否存在过。那么我们可以用两个比特位,甚至三个比特位。
实现
#pragma once
#include <stddef.h>
#include <stdint.h>
#define BloomType uint64_t
typedef uint64_t (*HashFun)(char*);
typedef struct BloomFilter {
BloomType* data;
uint64_t capacity;
HashFun fun[2];//哈希函数指针数组
} BloomFilter;
void BloomFilterInit(BloomFilter* bf, HashFun fun1, HashFun fun2);//初始化布隆过滤器
void BloomFilterDestroy(BloomFilter* bf);//销毁布隆过滤器
void BlommFilterSet(BloomFilter* bf, char* str);//根据字符串设置布隆过滤器
int BloomFilterIsExist(BloomFilter* bf, char* str);//判断字符串是否存在
#include "bloom_filter.h"
#include "bit_map.h"
#define BLOOMMAXSIZE 1000
uint64_t HashFun_131(char* msg) //哈希函数
{
if(msg == NULL) {
return 0;
}
char* str = msg;
uint64_t hash = 0;
while(*str) {
hash = hash*131 + *str;
str++;
}
return hash;
}
uint64_t HashFun_65599(char* msg)//哈希函数
{
if(msg == NULL) {
return 0;
}
char* str = msg;
uint64_t hash = 0;
while(*str) {
hash = hash*65599 + *str;
str++;
}
return hash;
}
void BloomFilterInit(BloomFilter* bf, HashFun fun1, HashFun fun2)//初始化布隆过滤器
{
if(bf == NULL) {
return;
}
bf->capacity = BLOOMMAXSIZE;
uint64_t size = GetSize(bf->capacity);
bf->data = (BloomType*)malloc(sizeof(BloomType) * size);
bf->fun[0] = fun1;
bf->fun[1] = fun2;
return;
}
void BloomFilterDestroy(BloomFilter* bf)//销毁布隆过滤器
{
if(bf == NULL) {
return;
}
bf->capacity = 0;
free(bf->data);
bf->data = NULL;
bf->fun[0] = NULL;
bf->fun[1] = NULL;
return;
}
void BlommFilterSet(BloomFilter* bf, char* str)//根据字符串设置布隆过滤器
{
if(bf == NULL) {
return;
}
uint64_t hash = bf->fun[0](str) % bf->capacity;
uint64_t offset = GetSize(hash);
uint64_t size = hash % (sizeof(BloomType) * 8);
bf->data[offset] |= (0x1ul << size);//设置两个比特位
hash = bf->fun[1](str) % bf->capacity;
offset = GetSize(hash);
size = hash % (sizeof(BloomType) * 8);
bf->data[offset] |= (0x1ul << size);
return;
}
int BloomFilterIsExist(BloomFilter* bf, char* str)//判断字符串是否存在
{
if(bf == NULL) {
return 0;
}
uint64_t hash = bf->fun[0](str) % bf->capacity;
uint64_t offset = GetSize(hash);
uint64_t size = hash % (sizeof(BloomType) * 8);
uint64_t ret1 = bf->data[offset] & (0x1ul << size);
hash = bf->fun[1](str) % bf->capacity;
offset = GetSize(hash);
size = hash % (sizeof(BloomType) * 8);
uint64_t ret2 = bf->data[offset] & (0x1ul << size);
if(ret1 != 0 && ret2 != 0) {//两个位同时为1
return 1;
} else {
return 0;
}
}
其实布隆过滤器在判断上,一定能判断某一个元素不在范围内。但是不一定能够判断某一个元素一定在范围内。所以在使用的时候要注意。
欢迎大家共同讨论,如有错误及时联系作者指出,并改正。谢谢大家!