djdangerousdick
djdangerousdick

Reputation: 63

Making a hash table the size of a user input

So from what I understand a hash table is pretty much an array of linked lists, so I am trying to make an array to be the size of a specific user input so if the user inputs '5' there will be 5 buckets (or indexes) in the hash table. The problem is that when I try to create the array in my .h file it says that the array length must be a constant. Should I define this somewhere else other than in the .h or is it possible to do it some other way? Thanks!

Here is my .h file:

#include <string>


using namespace std;

struct athlete{

    string discipline;
    string gender;
    string team;
    string event;
    string venue;
    string medal;
    string name;
    string country;
    athlete* next;

};


class hTable{

private:
    int tableSize; // need this to be user input
    athlete* HashTable[tableSize]; // hashTable is an array of athletes


public:
    hTable();
    int Hash(string key);  

Upvotes: 1

Views: 882

Answers (1)

Michael Albers
Michael Albers

Reputation: 3779

If you want a dynamically sized array it needs to be dynamically allocated.

HashTable = new athlete[tableSize];

And in the header file HashTable would be defined as:

athlete* HashTable;

It's probably better to use a std::unique_ptr as it makes memory clean up easier.

Usually std::vector is a preferred data structure than a plain array.

And for the record, a hash table is not just an array of linked lists.

Upvotes: 4

Related Questions