为哈希表初始化stl列表的动态数组(单独链接)

时间:2014-11-23 02:30:19

标签: c++ arrays hash stl initialization

我的程序在我的数组的特定索引处插入数据时抛出异常有问题。我正在使用哈希表,并尝试在指向另一个包含数据的类的指针数组中使用STL列表。 由于这是一个哈希表,我避免使用向量类,因为数组的大小应该是常量。 (我知道我想要的初始尺寸)

MCVE(为你):

    #ifndef HASHTABLE_H
    #define HASHTABLE_H

    #include <list>
    #include <cstring>
    #include <stdlib.h>
    template <typename T1>
    class HashTable
    {
      public:
           HashTable();
           void Insert(T1 var)
           int FindPrime(int);
           int HashFunction(string);
      private:
           int prime;
           list<T1> *List;
           int LF;
    }
    #endif

template <typename T1>
HashTable<T1>::HashTable()
{
  List[i] = list<T1>();
}

template <typename T1>
int HashTable<T1>::FindPrime(int num)
{
    bool isNotPrime = false;
    for (int i=num; i < num + 25; ++i)
    {
       for (int j=2; j<i; ++j)
        {
            if (i % j == 0)
                {
                    isNotPrime = true;
                }
        }

        if (isNotPrime == false)
            {
                    prime = i;
                    return prime;
                    break;
            }

        isNotPrime = false;
    }
        prime = num;
        return prime;
    }
    template <typename T1>
long HashTable<T1>::HashFunction(string key)
{
    long numkey = 0;    
    char word[1000];
    strcpy(word,key.c_str());
    word[sizeof(word) - 1] = NULL;              //Ensure null is at last index of word
    for(int i = 0; word[i] != NULL; ++i)
    {
        numkey = numkey + (word[i] * 101 + word[i]);
    }
    numkey = numkey % prime;
    return numkey;


}
    template <typename T1>
    void HashTable<T1>::Insert(T1 var)
    {
        int index = HashFunction(var -> getKey());
        List[index].push_front(var);
        ++LF;
        cout << "Load Factor: " << LF << endl << endl;
    }

来自确定如何处理数据的单独类:

file >> num;
hash.FindPrime(num);
file >> letter; // Get letter from file so we know what to do
    if(letter == 'D' || letter == 'd')  //If the letter is D, then add a new DNA Node with corresponding data to the STL List
        {   
            file >> Label >> ID >> Seq >> Length >> Index;
            cout << "Note: Adding " << Label << " ..." << endl << endl;
            Sequence* ptr = new DNA(Label, ID, Seq, Length, Index);
            hash.Insert(ptr);
            ptr = NULL;
            delete ptr;
        }   

Sequence Class是几个继承类的基类(DNA就是其中之一)

1 个答案:

答案 0 :(得分:1)

List[i]的类型为list<T1>。这就是编译器不允许您使用的原因:

List[i] = new list<T1>;
// Trying to assign a list<T1>* to a list<T1>.

您可以使用

List[i] = list<T1>();

list<T1>** List;