gpt4 book ai didi

c++ - 用数组和 C++ 字符串实现哈希算法 - 段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 02:46:00 28 4
gpt4 key购买 nike

当我的散列函数给出相似的散列值时,我收到“段错误(核心已转储)”错误。 “hash”和“Hash”函数都应该保持原样。 “keyValue”也是赋值的一部分,而不是确切的实现,但所有数字都应该是大写的(因此是“toUpper”函数)并且从 1 开始(例如 A=1、B=2 等)。我猜是“hashInsert”造成了问题,不幸的是我无法自己弄清楚。 (我应该使用数组)

#include <iostream>
#include <string>

using namespace std;

/**********************/
int toUpper( int );
int keyValue( int );
int hash( int );
int Hash( int );
int hashValue( string, int );
void hashInsert( string[], string );
/**********************/

const int days = 7;
string week[days];

int keyValue( int ch ){
return toUpper(ch) - 64;
}
int toUpper( int ch ){
if( ch >= 92 && ch <= 122 )
return ch - 32;
return ch;
}
int hash( int ch ){
return keyValue( ch ) % days;
}
int Hash( int ch ){
return 1 + (keyValue(ch) % (days-2));
}
int hashValue( string key, int i ){
return (hash(key[i]) + i*Hash(key[i]) % days);
}
void hashInsert( string table[], string key ){
int pos = 0;
for(int i=0; i < key.length(); i++){
pos = hashValue( key, i );
if( (table[pos]).empty() ){
table[pos] = key;
break;
}
}
}

/*=================== MAIN ===================*/
int main( int argc, char* argv[] ){

hashInsert( week, "Monday" );
// hashInsert( week, "Tuesday" );
// hashInsert( week, "Wednesday" );
hashInsert( week, "Thursday" );
// hashInsert( week, "Friday" );
hashInsert( week, "Saturday" );
hashInsert( week, "Sunday" );

cout << "0: " << week[0] << endl;
cout << "1: " << week[1] << endl;
cout << "2: " << week[2] << endl;
cout << "3: " << week[3] << endl;
cout << "4: " << week[4] << endl;
cout << "5: " << week[5] << endl;
cout << "6: " << week[6] << endl;


return 0;
}

最佳答案

hash(key[i]) + i*Hash(key[i]) % days 应该是 (hash(key[i]) + i*Hash(key[i ])) % 天

week[6] 相比,您正在访问 week 的元素。

关于c++ - 用数组和 C++ 字符串实现哈希算法 - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962727/

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