首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组和c++字符串散列算法的实现--分割故障(核转储)

数组和c++字符串散列算法的实现--分割故障(核转储)
EN

Stack Overflow用户
提问于 2014-05-30 20:15:30
回答 1查看 328关注 0票数 1

当我的散列函数给出类似的散列值时,我会得到“分段错误(核转储)”错误。“散列”和“哈希”函数都应该保持原样。"keyValue“也是赋值的一部分,而不是确切的实现,但是所有数字都应该是大写(因此是"toUpper”函数),从1开始(例如A=1、B=2等)。我想"hashInsert“就是那个制造问题的人,不幸的是,我无法自己解决这个问题。(我应该使用数组)

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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]更远。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23962727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档