Ok, I've been trying to wrap my head around this code for the longest time today, and I've tried to look up multiple web pages on how to solve my issue in a different way, but it's no use. There's something that Im not seeing that separates a regular array, from the way that I have my array or HashTable. The table is set to 128 slots as it's defined to that number. If you need any more information, let me know. My code is as following:
#include <iostream>
#include <iomanip>
using namespace std;
class HashEntry
{
private:
int key;
int value;
public:
HashEntry(int key, int value)
{
this->key=key;
this->value=value;
}
int getKey()
{
return key;
}
void setKey(int a_key)
{
key=a_key;
}
int getValue()
{
return value;
}
void setValue(int a_value)
{
value=a_value;
}
};
const int TABLE_SIZE =128;
class HashMap
{
private:
HashEntry**table;
public:
HashMap()
{
table=new HashEntry*[TABLE_SIZE];
for (int i=0;i<TABLE_SIZE;i++)
table[i]=NULL;
}
int get(int key)
{
int hash=(key % TABLE_SIZE);//check to see if the key is less or equal to 128
//While the spot in table is not null and there is a duplicate of key
while(table[hash]!=NULL && table[hash]->getKey()!=key)
//Increment the table spot to insert to
hash=(hash+1)&TABLE_SIZE;
//If there is no data
if(table[hash]==NULL)
return -1;
else
//return the value given there is a valid spot
return table[hash]->getValue();
}
void put(int key, int value)
{
//check to see if the key is within the array
int hash = (key % TABLE_SIZE);
//While the table spot isnt null and there is not already a key in place
while (table[hash] != NULL && table[hash]->getKey() != key)
//Increment the spot to insert data into on the table
hash = (hash + 1) % TABLE_SIZE;
//If it's null
if (table[hash] != NULL)
//delete that spot
delete table[hash];
//Create a new spot
table[hash] = new HashEntry(key, value);
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL)
delete table[i];
delete[] table;
}
int getSize()
{
int count=0;
for (int i=0;i<TABLE_SIZE;i++)
{
if(table[i]!=NULL)
count++;
else
break;
}
return count;
}
void insert(int key, int value)
{
int count=0;
for (int i=0;i<TABLE_SIZE;i++)
{
if(table[i]!=NULL)
//count the entries that have data
count++;
else
//If null, end loop
break;
}
if(key==-1)
table[count++]->setValue(value);
else
{
// count++;
for (int i=count;i>key;i--)
{
//Shift the data over
table[i]=table[i-1];
}
//Put the data back in the empty slot.
table[key]->setValue(value);
//put(key,value);
}
}
};
void main()
{
HashMap Bob;
Bob.put(0,0);
Bob.put(1,10);
Bob.put(2,20);
Bob.put(3,40);
Bob.put(4,100);
for (int i=0;i<Bob.getSize();i++)
{
cout << Bob.get(i) << endl;
}
Bob.insert(1,30);
cout << "\nNew Numbers" << endl;
for (int i=0;i<10;i++)
{
cout << Bob.get(i) << endl;
}
}