HashTable实现的错误结果
Wrong result in HashTable Implementation
我编写了下面的代码来实现HashTable链算法,但当我在main
函数中使用它时,结果是错误的:
#define _SIZE 1000
class HashEntry
{
public: int Tel;
string Name;
public: HashEntry(){}
public: HashEntry(int Tel, string Name)
{
this->Tel = Tel;
this->Name = Name;
}
};
class Link {
public:
HashEntry data;
Link *next;
public:
Link() : next(NULL){ }
};
void Insert (Link *head, HashEntry data)
{
Link *t= new Link;
t->data=data;
if(head==NULL)
{
head = new Link;
head->next = NULL;
head->data = data;
return;
}
Link *head2= head;
while(head2->next!=NULL)
{
if( head2->data.Name == data.Name)
return;
head2=head2->next;
}
head2->next=t;
}
class HashTable {
public:
Link **a;
public:
HashTable()
{
a = new Link *[_SIZE];
for (int i=0; i<_SIZE; i++)
a[i]=NULL;
}
public:
int HashFonction (string key)
{
int res=0;
for ( int i = 0; i < key.length(); i ++ )
{
char ch = key.at(i);
if( i%2==0)
res+=(int)ch;
else
res-=(int)ch;
}
return (int)fabsf((float)res) % _SIZE;
}
void HashInsert (string key, int val){
int index= HashFonction(key);
HashEntry s(val, key);
Insert(a[index],s);
}
int HashSearch(string key)
{
int inx=HashFonction(key);
Link *head=a[inx];
if(head==NULL){
return -1;
}
while(head!=NULL){
if(head->data.Name==key)
return head->data.Tel;
head=head->next;
}
return -1;
}
};
实现该类后,我编写了以下代码,但搜索的结果是-1:-/
HashTable ht;
ht.HashInsert("Hossein", 849348);
ht.HashInsert("Ali", 94343);
ht.HashInsert("Fatemeh", 940343);
cout << ht.HashSearch("Ali") << endl; // output = -1 :-/
谁能解释一下出了什么问题?
谢谢你的关注
你的问题是
void Insert (Link * head, HashEntry data)
改为
void Insert (Link *& head, HashEntry data)
基本上指针是通过值
传递的你想做的事等于
void Bar( Link* input )
{
input = new Link();
}
Link* foo = 0;
Bar( foo );
Bar返回后foo 仍然是0。当按值传递指针时,可以修改指针所指向的内容,而不是指针本身。要使上述内容按预期工作,可以执行
备选项1
通过指针通过引用传递
void Bar( Link*& input )
{
input = new Link();
}
Link* foo = 0;
Bar( foo );
ALTERNATIVE 2
传递指针给指针
void Bar( Link** input )
{
*input = new Link();
}
Link* foo = 0;
Bar( &foo );
将指针头传递给按值插入函数,因此类哈希表中的数组"a"不会改变。通过引用传递解决了这个问题:
void Insert (Link *&head, HashEntry data)
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- Static_cast转换为错误的数据类型,但结果仍然正确?
- C++ 犰狳库中的sort_index()函数给出了错误的结果
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- 为什么我的性能基准给了我错误的结果?
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 斐波那契检验(C++)的结果错误
- 在发布版本中划分两个双精度的结果错误
- 2D FFT后的图像结果错误
- 计算文本文件中的单个字母并打印结果 - 错误的输出 C++
- C++字符和 int 之间的转换,结果错误
- char*与std字符串的比较结果错误
- 斯波吉购物结果错误
- 超载"+"操作员,结果错误?
- 执行高斯消去程序时结果错误
- hash_djb2 PHP结果错误
- 按位操作比较结果错误
- 使用'if'语句和"<<"时的结果错误,'>>'运算符比较 3 个整数