我从字符串数组中创建一个哈希表,在我的插入中,我有一个while语句来处理冲突和环绕。我玩过它,并且在使用条件语句时似乎只得到分段错误11。继承了我的while循环:
while (numElm != length)
{
numProbes = 0;
int index = hash( newGuest );
//handles collision and wraparound
while (hashArray[index] != " " && hashArray[index] != "-1")
{
++index;
index %= length;
numProbes = numProbes + 1;
}
//sets the array at the index eqaul to data
hashArray[index] = newGuest;
cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes";
break;
}
当第二个while循环以两个条件语句开头时,会出现问题。谁能告诉我为什么会这样?
编辑该计划的其余部分
#include <cassert>
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <string>
#include "HashTable.h"
using namespace std;
//typedef double value_type;
HashTable::HashTable( int tableLength )
{
tableLength = 114;
string *hashArray = new string[tableLength];
length = tableLength;
numElm = 0;
for(int i = 0; i < length; i++)
{
hashArray[i] = " ";
}
}
// Returns an array location for a given item key.
int HashTable::hash( string itemKey )
{
int value = 0;
for (int i = 0; i < itemKey.size(); i++ )
{
value += itemKey[i];
}
return (value * itemKey.length() ) % length;
}
// Adds an item to the Hash Table.
void HashTable::insertGuest( string newGuest )
{
// int index = hash( newGuest );
//hashArray[ index ].insertGuest( newGuest );
// cout << newGuest << " has been inserted at index: " << index;
// string s = " ";
while (numElm != length)
{
numProbes = 0;
int index = hash( newGuest );
//handles collision and wraparound
while (hashArray[index] != " " && hashArray[index] != "-1")
{
++index;
index %= length;
numProbes = numProbes + 1;
}
//sets the array at the index eqaul to data
hashArray[index] = newGuest;
cout << newGuest << " has been inserted at index: " << index << " using " << numProbes << " probes";
break;
}
}
// De-allocates all memory used for the Hash Table.
HashTable::~HashTable()
{
delete [] hashArray;
}
//#endif
答案 0 :(得分:2)
您没有在构造函数中初始化成员变量hashArray
,只初始化本地变量hashArray
。类中的hashArray
保持未初始化状态,并在使用时导致崩溃。要修复,请替换
string *hashArray = new string[tableLength];
与
hashArray = new string[tableLength];
这解决了这个问题。代码有许多风格和代码方面的问题,但我希望你会继续学习如何自己解决这些问题。祝你好运!