gpt4 book ai didi

c++ - 由于 while 循环中的条件而导致段错误

转载 作者:行者123 更新时间:2023-11-28 01:52:56 25 4
gpt4 key购买 nike

我用字符串数组制作哈希表,在我的插入中,我有一个 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

最佳答案

您不初始化您的成员 变量hashArray,只在您的构造函数中初始化一个本地 变量hashArray。您类中的 hashArray 保持未初始化状态,并在使用时导致崩溃。要修复,更换

string *hashArray = new string[tableLength];

hashArray = new string[tableLength];

这解决了问题。否则代码有很多风格和代码方面的问题,但我希望你能继续学习自己解决这些问题。祝你好运!

关于c++ - 由于 while 循环中的条件而导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42220292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com