AntInLoop

Bloom Filter (Probabilistic Set) Code Implementations

Production-ready Bloom Filter (Probabilistic Set) data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.

Study Bloom Filter (Probabilistic Set) Guide ยท Launch Visualizer

CPP Implementation

#include <vector>
#include <cmath>

// A simple C++ implementation of Bloom Filter

class BloomFilter {
    std::vector<bool> filter;
    int filterSize;

public:
    // Constructor to initialize the Bloom Filter
    BloomFilter(int size) {
        filterSize = size;
        filter.resize(filterSize, false);
    }

    // Insert an element into the Bloom Filter
    void insert(int num) {
        // Apply two hash functions and set the corresponding bits
        filter[num % filterSize] = true;
        filter[(num / 2) % filterSize] = true;
    }

    // Search for an element in the Bloom Filter
    bool search(int num) {
        // Apply the same hash functions and check if the bits are set
        if (filter[num % filterSize] && filter[(num / 2) % filterSize])
            return true;
        else
            return false;
    }

    // Check if the Bloom Filter is empty
    bool isEmpty() {
        for (int i = 0; i < filterSize; i++)
            if (filter[i])
                return false;
        return true;
    }

    // Get the size of the Bloom Filter
    int size() {
        return filterSize;
    }
};