【发布时间】:2015-01-20 23:49:56
【问题描述】:
在我的数组的特定索引处插入数据时,我的程序抛出异常时遇到问题。我正在使用哈希表,并尝试在指向另一个包含数据的类的指针数组中使用 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;
}
序列类是几个继承类的基类(DNA就是其中之一)
【问题讨论】:
-
我不明白你为什么不只使用
std::vector<std::list<T1>>并将向量的初始大小设置为你想要的素数。结果将是一个空列表表,考虑到您避免了自己手动管理内存的所有潜在问题,这似乎是可取的(当然,std::unordered_map<>会直接解决这个问题,但这似乎更像是一种练习而不是目标生产代码)。如果您仍然坚持手动内存管理的自虐目标,R.Sahu 似乎为您提供了答案。 -
@WhozCraig 我可以,但我更喜欢尝试了解底层基础知识,而不是总是依赖标准库为我做这件事。在使用 STL 列表之前,我自己为以前的项目编写了一个链表,我对它的理解要好得多。我只是更喜欢这种学习方式。
标签: c++ arrays hash stl initialization