繁体   English   中英

使用数组和c ++字符串实现散列算法 - 分段错误(核心转储)

[英]Implementation of hashing algorithm with arrays and c++ strings - Segmentation fault (core dumped)

当我的哈希函数给出类似的哈希值时,我收到“Segmentation fault(core dumped)”错误。 “哈希”和“哈希”函数都应该保持原样。 “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])) % days

你访问week元素比week[6]更进一步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM