從一個字符串數組中創建一個哈希表,並在我的插入中,我有一個while語句可以處理碰撞和環繞。我玩過它,似乎只在使用條件語句時纔會出現分段錯誤11。下面是我的while循環:由於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
什麼是'hashArray'聲明?事實上。請給出一個完整的[mcve]。 – BoBTFish
你的'index'明顯超出'hashArray'。試過調試? – arrowd
你確定'hash(newGuest)'總是返回一個不在數組邊界之外的有效索引嗎? – sigy