Hash Set Data Structure Code Implementations
Production-ready Hash Set Data Structure data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.
Study Hash Set Data Structure Guide ยท Launch Visualizer
CPP Implementation
#include<bits/stdc++.h>
using namespace std;
// Hash Set Class
class HashSet {
private:
vector<list<int>> data; // The main data structure to store elements
int capacity; // The capacity of the hash set
public:
// Constructor
HashSet(int capacity) {
this->capacity = capacity;
data = vector<list<int>>(capacity);
}
// Function to insert a value into the hash set
void insert(int value) {
int index = value % capacity; // Calculate the index
data[index].push_back(value); // Insert the value
}
// Function to remove a value from the hash set
void remove(int value) {
int index = value % capacity; // Calculate the index
data[index].remove(value); // Remove the value
}
// Function to search for a value in the hash set
bool search(int value) {
int index = value % capacity; // Calculate the index
for(int x : data[index])
if(x == value)
return true;
return false;
}
// Function to get the size of the hash set
int size() {
int size = 0;
for(int i = 0; i < capacity; i++)
size += data[i].size();
return size;
}
// Function to check if the hash set is empty
bool isEmpty() {
return size() == 0;
}
};