当我的散列函数给出类似的散列值时,我会得到“分段错误(核转储)”错误。“散列”和“哈希”函数都应该保持原样。"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;
}发布于 2014-05-30 20:21:51
hash(key[i]) + i*Hash(key[i]) % days应该是(hash(key[i]) + i*Hash(key[i])) % days。
您访问week元素的方式要比week[6]更远。
https://stackoverflow.com/questions/23962727
复制相似问题