I am trying to make a template hash table that uses an array of lists to store data. for the table I am trying to write an insert function for hash table that creates a new list if the hash index points to a section that does not already have a list in it.
here is the basics of the class:
template <class T>
class Hash
{
public:
Hash(int buckets);
Hash(const Hash <T> & rhs);
~Hash() { delete [] table; }
/*some functions removed for brevity*/
void insert(const T & t); //this is the function I am struggling with
virtual int hash(const T & t) const = 0;
private:
list <T> * table;
int numElements;
int numBuckets;
};
here is my attempt at the insert function:
//insert
template <class T>
void Hash <T> :: insert(const T & t)
{
if (table[hash(t)] == NULL) // I am not comparing this right
{
//compiler does not like this assignment
table[hash(t)] = new list <T>;
//insert passed in value into new list
table[hash(t)].insert(hash(t));
}
else
{
//insert passed in value into list
table[hash(t)].insert(hash(t));
}
numElements++;
}
It is my understanding that my private variable list * table can act as an array.
My questions are: how do I look inside the table variable correctly to see if there is a list created there or not and how do I create a new list at the passed in hash index
edit here is my constructor definition and a hash class of ints:
I am using a non default constructor to get the number of "buckets" that the user wants in the hash table:
//non-default constructor
template <class T>
Hash <T> :: Hash(int buckets)
{
table = new list <T> [buckets];
numElements = 0;
numBuckets = buckets;
}
here is the integer hash class:
/****************************************
* I HASH
* A simple hash of integers
****************************************/
class IHash : public Hash <int>
{
public:
IHash(int numBuckets) : Hash <int> (numBuckets) {}
IHash(const IHash & rhs) : Hash <int> (rhs) {}
// hash function for integers is simply to take the modulous
int hash(const int & value) const
{
int index = abs(value) % capacity();
assert(0 <= index && index < capacity());
return index;
}
};
std::vector
orstd::array
, right? Then I would suggest you to learn about dynamic arrays first. Most importantly: a pointer is not an array – 463035818_is_not_a_numberhash
calculation. – 1201ProgramAlarmdelete [] table
) but you never create one – 463035818_is_not_a_number