位图和布隆过滤器

1.位图的概念

所谓位图,就是用每一位来存放某种状态,适用于海量数据,数据无重复的场景。通常是用 来判断某个数据存不存在的。

2.位图的应用

1. 快速查找某个数据是否在一个集合中

2. 排序 + 去重

3. 求两个集合的交集、并集等

4. 操作系统中磁盘块标记

#pragma once

#include<vector>
#include<iostream>

using namespace std;

template<size_t N>
class bite
{
	bite()
	{
		bit.resize(N /32 + 1, 0);
	}
	void set(size_t x)
	{
		//例如:100,要插入到bit[3]中的那个整数第4位,把那个位置改成1,整数由32位比特位组成
		size_t i = x / 32;
		size_t j = x % 32;
		bit[i] |= (1 << j);
	}
	bool test(size_t x)
	{
		size_t i = x / 32;
		size_t j = x % 32;
		bit[i] & (1 << j);
	}
private:
	vector<int> bit;
};

3.布隆过滤器的概念

布隆过滤器是由布隆(Burton Howard Bloom)在1970年提出的 一种紧凑型的、比较巧妙的概 率型数据结构,特点是高效地插入和查询,可以用来告诉你 “某样东西一定不存在或者可能存 在”,它是用多个哈希函数,将一个数据映射到位图结构中。此种方式不仅可以提升查询效率,也 可以节省大量的内存空间。

4.布隆过滤器的查找

布隆过滤器的思想是将一个元素用多个哈希函数映射到一个位图中,因此被映射到的位置的比特 位一定为1。所以可以按照以下方式进行查找:分别计算每个哈希值对应的比特位置存储的是否为 零,只要有一个为零,代表该元素一定不在哈希表中,否则可能在哈希表中。 注意:布隆过滤器如果说某个元素不存在时,该元素一定不存在,如果该元素存在时,该元素可 能存在,因为有些哈希函数存在一定的误判。

5.布隆过滤器删除

布隆过滤器不能直接支持删除工作,因为在删除一个元素时,可能会影响其他元素。

#pragma once

#include<vector>
#include<iostream>

using namespace std;

template<size_t N>
class bite
{
public:
	bite()
	{
		bit.resize(N /32 + 1, 0);
	}
	void set(size_t x)
	{
		//例如:100,要插入到bit[3]中的那个整数第4位,把那个位置改成1,整数由32位比特位组成
		size_t i = x / 32;
		size_t j = x % 32;
		bit[i] |= (1 << j);
	}
	bool test(size_t x)
	{
		size_t i = x / 32;
		size_t j = x % 32;
		return bit[i] & (1 << j);
	}
private:
	vector<int> bit;
};


struct BKDRHash
{
	size_t operator()(const string& key)
	{
		// BKDR
		size_t hash = 0;
		for (auto e : key)
		{
			hash *= 31;
			hash += e;
		}

		return hash;
	}
};

struct APHash
{
	size_t operator()(const string& key)
	{
		size_t hash = 0;
		for (size_t i = 0; i < key.size(); i++)
		{
			char ch = key[i];
			if ((i & 1) == 0)
			{
				hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
			}
			else
			{
				hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
			}
		}
		return hash;
	}
};

struct DJBHash
{
	size_t operator()(const string& key)
	{
		size_t hash = 5381;
		for (auto ch : key)
		{
			hash += (hash << 5) + ch;
		}
		return hash;
	}
};


template<size_t N,
	class K=string,
	class HashFun1=BKDRHash,
	class HashFun2=APHash,
	class HashFun3=DJBHash>
class BloomFilter
{
public:
	void set(const K& key)
	{
		size_t x = HashFun1()(key) % N;
		size_t y = HashFun2()(key) % N;
		size_t z = HashFun3()(key) % N;
		bs.set(x);
		bs.set(y);
		bs.set(z);
	}

	bool test(const K& key)
	{
		size_t x = HashFun1()(key) % N;
		if (bs.test(x) == false) return false;
		size_t y = HashFun2()(key) % N;
		if (bs.test(y) == false) return false;
		size_t z = HashFun3()(key) % N;
		if (bs.test(z) == false) return false;

		return true;
	}
private:
	bite<N> bs;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sakura&NANA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值