测试完美哈希函数时超出范围错误

Out of Scope Error when Testing Function for Perfect Hash

本文关键字:范围 错误 完美 哈希 函数 测试      更新时间:2023-10-16

我正在尝试测试我的哈希项目的一个功能。此函数的目标是从包含 1000 个字符串的列表为字符串创建索引。它应该将字符串中每个字符的 ASCII 值相加,将其乘以随机数 (int c( 并将其取模素数 (int prime1( 以找到哈希中的索引。我正在尝试使用字符串"hi"测试此代码,但是每当我这样做时,我都会不断得到一个超出范围的函数错误。我不明白为什么,因为主函数就在它试图测试的函数下面。

这是我的课

 //using namespace std;
 #ifndef HASH_H
 #define HASH_H
 class hash{
 // Public Member functions
 public:
 hash(); // Constructor
 int  CreateG(const std::string city);
 int  HashFunction(std::string city); // the declaration of the hash function for the primary hash
 // Private member functions
 private:

 // Protected Member functions
 protected:
 }
 #endif 

这是我的.cpp

#include <cstdlib>
#include <iostream>
#include <string>
#include "Hash.h"
//using namespace std;
int  hash::HashFunction(std::string city){ // the declaration of the hash function for the primary hash

} 
int hash::CreateG(const std::string city){ // creates g(str) to use in the universal hash function 
    int prime1 = 16890581;
    int c = rand()%10; // This is the random number c to use when finding g 
    int g = 0; // initial value of g
    int x=0; // This is the sum of all the ascii values
    // Create a for loop, to iterate from 1 to 1000 (1000 because that this how many cities are in the input file)
    for(int i=1; i<=1000; i++){
        for( int t = 1; i < city.length(); t++ ) // for loop that runs through the string
        {
            char ch=city.at(i);
            int x=x+(int)ch; // This should be the running summation of the ascii values of the chars of the strings
        }
    }
    g = (x*c)%prime1;
    std::cout<<g;
    return g; // returns the value of 
}    

int main(){
    std:: string test = "hi";
    std::cout<<CreateG(test);
}

这是我的错误

   /home/ec2-user/environment/.c9/Project4/Hash.cpp:53:31: error: 
   ‘CreateG’ was not declared in this scope
    std::cout<<CreateG(test);
                           ^

CreateGhash类的方法,而不是独立的函数。

您必须实例化hash才能使用它。

int main(){
    std:: string test = "hi";
    hash h;
    std::cout<<h.CreateG(test);
}

Federico 说:CreateG是一个非静态成员函数,但你试图像非成员函数一样使用它。(复习C++书中的课程

也:

int x=x+(int)ch; // This should be the running summation of the ascii values of the chars of the strings

它不能是正在运行的求和,因为您重新声明了新的本地x(因此也在 RHS 上使用未初始化的值(。

请改为删除要分配给现有xint