使哈希表的大小与用户输入

时间:2016-10-05 01:15:18

标签: c++ linked-list hashtable

所以根据我的理解,哈希表几乎是一个链表的数组,所以我试图使一个数组成为特定用户输入的大小,所以如果用户输入' 5'哈希表中将有5个桶(或索引)。问题是,当我尝试在我的.h文件中创建数组时,它表示数组长度必须是常量。我应该在除了.h之外的其他地方定义它,还是可以用其他方式做到这一点?谢谢!

这是我的.h文件:

#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);  
  • 我也为语法道歉英语不是我的第一语言

1 个答案:

答案 0 :(得分:4)

如果你想要一个动态大小的数组,它需要动态分配。

HashTable = new athlete[tableSize];

在头文件HashTable中将定义为:

athlete* HashTable;

使用std::unique_ptr可能会更好,因为它可以让内存更容易清理。

通常std::vector是首选数据结构而不是普通数组。

对于记录,哈希表不仅仅是链表的数组。