This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBloom_Filter.cpp
51 lines (51 loc) · 1.59 KB
/
Bloom_Filter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <bitset>
#include <functional>
#include <vector>
class BloomFilter {
private:
std::vector<bool> bitArray;
std::vector<std::function<size_t(const std::string&)>> hashFunctions;
size_t numHashFunctions;
public:
BloomFilter(size_t size, size_t numHashFunctions)
: bitArray(size, false), numHashFunctions(numHashFunctions) {
initializeHashFunctions();
}
void insert(const std::string& element) {
for (const auto& hashFunction : hashFunctions) {
size_t index = hashFunction(element) % bitArray.size();
bitArray[index] = true;
}
}
bool contains(const std::string& element) const {
for (const auto& hashFunction : hashFunctions) {
size_t index = hashFunction(element) % bitArray.size();
if (!bitArray[index]) {
return false;
}
}
return true;
}
private:
void initializeHashFunctions() {
hashFunctions.push_back(std::hash<std::string>());
hashFunctions.push_back(hashFunction1);
}
static size_t hashFunction1(const std::string& str) {
size_t hash = 0;
for (char c : str) {
hash = hash * 31 + c;
}
return hash;
}
};
int main() {
BloomFilter bloomFilter(100, 3);
bloomFilter.insert("apple");
bloomFilter.insert("orange");
bloomFilter.insert("banana");
std::cout << "Contains 'apple': " << bloomFilter.contains("apple") << std::endl;
std::cout << "Contains 'grape': " << bloomFilter.contains("grape") << std::endl;
return 0;
}