系列: Algorithms
cpp
44 行
· 更新於 2026-04-18
bloom_filter.cpp
Algorithms/Hash/cpp/bloom_filter.cpp
/**
* Simple Bloom filter: m bits, k hash seeds derived from std::hash + salt.
*/
#include <bitset>
#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
template <std::size_t M, std::size_t K>
class BloomFilter {
std::bitset<M> bits_{};
static std::size_t h(std::size_t seed, const std::string& x) {
std::size_t a = std::hash<std::string>{}(x);
std::size_t b = seed * 0x9e3779b97f4a7c15ULL + 1;
return (a ^ b) % M;
}
public:
void insert(const std::string& key) {
for (std::size_t i = 0; i < K; ++i) bits_.set(h(i, key));
}
bool maybeContains(const std::string& key) const {
for (std::size_t i = 0; i < K; ++i) {
if (!bits_.test(h(i, key))) return false;
}
return true;
}
};
int main() {
constexpr std::size_t M = 1024;
constexpr std::size_t K = 4;
BloomFilter<M, K> bf;
bf.insert("alice");
bf.insert("bob");
std::cout << std::boolalpha;
std::cout << "alice? " << bf.maybeContains("alice") << "\n";
std::cout << "bob? " << bf.maybeContains("bob") << "\n";
std::cout << "carol? " << bf.maybeContains("carol") << " (may false positive)\n";
return 0;
}
相關文章
Algorithms
java
更新於 2026-03-02
#include <iostream>.java
#include <iostream>.java — java source code from the Algorithms learning materials (Algorithms/#include <iostream>.java).
閱讀文章 →
Algorithms
cpp
更新於 2026-04-07
748.cpp
748.cpp — cpp source code from the Algorithms learning materials (Algorithms/748.cpp).
閱讀文章 →
Algorithms
cpp
更新於 2026-04-07
827.cpp
827.cpp — cpp source code from the Algorithms learning materials (Algorithms/827.cpp).
閱讀文章 →
Algorithms
cpp
更新於 2026-04-07
827_best_greedy.cpp
827_best_greedy.cpp — cpp source code from the Algorithms learning materials (Algorithms/827_best_greedy.cpp).
閱讀文章 →
Algorithms
cpp
更新於 2026-04-07
8402.cpp
8402.cpp — cpp source code from the Algorithms learning materials (Algorithms/8402.cpp).
閱讀文章 →
Algorithms
cpp
更新於 2026-04-07
860.cpp
860.cpp — cpp source code from the Algorithms learning materials (Algorithms/860.cpp).
閱讀文章 →