C++ 实现布隆过滤器(BloomFilter)
生活随笔
收集整理的這篇文章主要介紹了
C++ 实现布隆过滤器(BloomFilter)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
#include <iostream> #include <vector> 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為哈希函數的個數struct HashFun1 {size_t operator()(const string & str){size_t hash = 0;for (const auto & ch : str){hash = hash * 131 + ch;}return hash;} };struct HashFun2 {size_t operator()(const string & str){size_t hash = 0;for (const auto & ch : str){hash = hash * 65599 + ch;}return hash;} };struct HashFun3 {size_t operator()(const string & str){size_t hash = 0;for (const auto & ch : str){hash = hash * 1313131 + ch;}return hash;} };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; };總結
以上是生活随笔為你收集整理的C++ 实现布隆过滤器(BloomFilter)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样拍摄背景全黑的照片
- 下一篇: 只听说过给电脑打补丁如何电脑打补丁