布隆过滤器 模拟
#pragma once
#include <bitset>
#include <string>
namespace sjy
{
template<class K>
size_t BKDRHash(const K* str)
{
register size_t hash = 0;
while (size_t ch = (size_t)*str++)
{
hash = hash * 131 + ch;
}
return hash;
}
template<class K>
size_t APHash(const K* str)
{
register size_t hash = 0;
size_t ch;
for (long i = 0; ch = (size_t)*str++; i++)
{
if ((i & 1) == 0)
{
hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
}
else
{
hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
}
}
return hash;
}
template<class K>
size_t DJBHash(const K* str)
{
if (!*str)
{
return 0;
}
register size_t hash = 5381;
while (size_t ch = (size_t)*str++)
{
hash += (hash << 5) + ch;
}
return hash;
}
template <typename K>
struct HashFunc1
{
size_t operator()(const K& key)
{
return BKDRHash(&key);
}
};
template <typename K>
struct HashFunc2
{
size_t operator()(const K& key)
{
return APHash(&key);
}
};
template <typename K>
struct HashFunc3
{
size_t operator()(const K& key)
{
return DJBHash(&key);
}
};
template <size_t N, typename K = string,
typename Hash1 = HashFunc1<string>,
typename Hash2 = HashFunc2<string>,
typename Hash3 = HashFunc3<string>>
class BloomFilter
{
public:
void set(const K& key)
{
size_t hash1 = HashFunc1<K>()(key) % N;
size_t hash2 = HashFunc2<K>()(key) % N;
size_t hash3 = HashFunc3<K>()(key) % N;
_bs.set(hash1);
_bs.set(hash2);
_bs.set(hash3);
}
bool test(const K& key)
{
size_t hash1 = HashFunc1<K>()(key) % N;
if (_bs.test(hash1) == false)
{
return false;
}
size_t hash2 = HashFunc2<K>()(key) % N;
if (_bs.test(hash2) == false)
{
return false;
}
size_t hash3 = HashFunc3<K>()(key) % N;
if (_bs.test(hash3) == false)
{
return false;
}
return true;
}
private:
bitset<N> _bs;
};
}