I am trying to learn C++ and trying to write a code for a simple hash table like following structure:
array[0][0] array[0][1] array[0][2]
key 1 value 1 value 2
array[1][0] array[1][1]
key 2 value 3
array[2][0] array[2][1] array[2][2]
key 3 value 4 value 5
means Array of Dynamic Arrays. Now, below is my code:
#include<iostream>
#include<conio.h>
using namespace std;
int ele [10] ;
int** arrays = new int*[10] ;
class HashTable
{
public:
HashTable()
{
for(int i = 0 ; i < 10 ; i++)
ele[i] = - 1 ; // element array stores the number of elements in column of each row
}
void put(int key, int value){
if(ele[key] == -1){
arrays[key] = new int[1];
arrays[key][0] = value ; // initialize 2nd dimention
ele[key] = 0 ;
}
else{
int num = ele[key] ;
int temp[num + 1] ;
for(int i = 0 ; i < num ; i++)
temp [i] = arrays[key][i] ;
temp[num+1] = value ;
arrays[key] = new int[num + 1] ;
for(int i = 0 ; i < num+1 ; i++) // take all the elements in an temporary array and store it back
arrays[key][i] = temp [i] ;
ele[key] = num + 1 ;
}
}
};
main()
{
HashTable object;
object.put(0 , 100);
object.put(1 , 200);
object.put(3 , 300);
object.put(3 , 3000);
object.put(3 , 30000);
object.put(5 , 500);
object.put(5 , 5000);
object.put(5 , 50000);
object.put(5 , 50);
for (int i = 0 ; i < 10 ; i++ ){
int j = ele[i] ;
cout << j << " K ";
if(j != -1){
for (int k = -1 ; k < j ; k++ ) // print the values of corresponding keys
cout << arrays[i][k] << " ";
}
}
getch();
return 0;
}
which uses put method to put values in the custom HashTable.
Can anybody help me why above code gives wrong output value while trying to retrieve values of the corresponding key.
This can’t work:
You cannot have arrays with negative indexes. When you enter the loop, you have
k = -1so you try to accessarrays[i][-1], which won’t work.Other recommendations:
arraysandeleshould be members of your class and be declared inside it (as private members)arrays[key] = new int[num + 1], you forget to calldeleteon the previous object. This will cause a memory leak.arraysusing a method inside your function (like theputmethod) and then just call it usingobject.print()(if you named itprint)if(j != -1)before the loopfor (int k = -1; k < j; k++)is redundant: ifj == -1you will never go into the loop anyway.