I am trying to implement hashing in C++ from scratch. Everything seems to be fine except the output. I am implementing hashing using chaining. This style of hashing uses a linked list for handling collisions. I used an array of linked lists of the type HashNode which I defined inside the HashTable class.
#include <bits/stdc++.h>
using namespace std;
template<class K,class V>
class HashTable{
class HashNode{
friend class HashTable;
public:
K key;
V val;
HashNode(K key, V val){
this->key = key;
this->val = val;
}
K getKey(){
return this->key;
}
V getVal(){
return this->val;
}
};
int cap;
list<HashNode>* ptr = new list<HashNode>[cap];
public:
//constructor
HashTable(int x){
cap = x;
}
//hash function
hash<K> hashIt;
int getHash(K k){
return hashIt(k)%cap;
}
//adding pair
void addPair(K k, V v){
int index = getHash(k);
bool found = false;
auto bucket = *(ptr + index);
for(auto x = bucket.begin();x!=bucket.end();x++){
if((*x).key == k){
(*x).val = v;
found = true;
break;
}
}
if(!found){
bucket.push_back(HashNode(k,v));
}
}
//display function
void display(){
for(int i=0;i<cap;i++){
cout<<"\n Bucket " + i<<" =>"<<endl;
auto bucket = *(ptr + i);
for(auto x = bucket.begin();x!=bucket.end();x++ ){
cout<<(*x).getKey()<<" : "<<(*x).getVal()<<endl;
}
}
}
};
int main(){
HashTable<string,int> H(13);
H.addPair("IND",20);
H.addPair("PAK",10);
H.display();
}
However, when I run the program, I get the following output
Bucket =>
Bucket =>
Bucket =>
ucket =>
cket =>
ket =>
et =>
t =>
=>
=>
=> =>
=> =>
> =>
It would be helpful if anyone could point out the mistake.