|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <bitset> |
| 4 | +#include <functional> |
| 5 | + |
| 6 | +class BloomFilter { |
| 7 | +private: |
| 8 | + int size; // Size of the Bloom Filter bitset |
| 9 | + std::vector<std::function<size_t(const std::string&)>> hash_functions; |
| 10 | + std::bitset<1000000> bitset; // Bitset to represent the Bloom Filter |
| 11 | + |
| 12 | +public: |
| 13 | + // Constructor to initialize the Bloom Filter with a given size and hash functions |
| 14 | + BloomFilter(int size, std::vector<std::function<size_t(const std::string&)>> hash_functions) |
| 15 | + : size(size), hash_functions(hash_functions) {} |
| 16 | + |
| 17 | + // Function to add an element to the Bloom Filter |
| 18 | + void add(const std::string& element) { |
| 19 | + for (const auto& hash_function : hash_functions) { |
| 20 | + size_t index = hash_function(element) % size; |
| 21 | + bitset.set(index); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Function to check if an element may exist in the Bloom Filter |
| 26 | + bool contains(const std::string& element) { |
| 27 | + for (const auto& hash_function : hash_functions) { |
| 28 | + size_t index = hash_function(element) % size; |
| 29 | + if (!bitset.test(index)) { |
| 30 | + return false; // If any bit is not set, the element is definitely not in the filter |
| 31 | + } |
| 32 | + } |
| 33 | + return true; // If all bits are set, the element may exist in the filter (false positives are possible) |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +// Example hash function using std::hash |
| 38 | +size_t hash1(const std::string& str) { |
| 39 | + return std::hash<std::string>{}(str); |
| 40 | +} |
| 41 | + |
| 42 | +// Example hash function using a custom hash function |
| 43 | +size_t hash2(const std::string& str) { |
| 44 | + size_t hash = 0; |
| 45 | + for (char c : str) { |
| 46 | + hash = (hash * 31) + c; |
| 47 | + } |
| 48 | + return hash; |
| 49 | +} |
| 50 | + |
| 51 | +int main() { |
| 52 | + // Create a Bloom Filter with a size of 1000000 and two hash functions |
| 53 | + BloomFilter bloomFilter(1000000, {hash1, hash2}); |
| 54 | + |
| 55 | + // Add elements to the Bloom Filter |
| 56 | + bloomFilter.add("apple"); |
| 57 | + bloomFilter.add("banana"); |
| 58 | + bloomFilter.add("cherry"); |
| 59 | + |
| 60 | + // Check if elements may exist in the Bloom Filter |
| 61 | + std::cout << "Contains 'apple': " << bloomFilter.contains("apple") << std::endl; // Should return 1 (true) |
| 62 | + std::cout << "Contains 'grape': " << bloomFilter.contains("grape") << std::endl; // Should return 0 (false) |
| 63 | + std::cout << "Contains 'cherry': " << bloomFilter.contains("cherry") << std::endl; // Should return 1 (true) |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments