问题描述
我想编写一些代码,将数组中的元素插入下面的哈希表中。我将数组“a”用作测试数组,以查看是否可以将元素插入哈希表中。然而,当我运行代码时,只有第一个元素被插入到哈希表中,其余的键保持为空。
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
struct table
{
int key;
int val;
table()
{
}
table(int k,int v)
{
key = k;
val = v;
}
};
void INSERT(table T[],table x)
{
T[x.key] = x;
}
void DELETE(table T[],table x)
{
T[x.key] = table(0,0);
}
table SEARCH(table T[],int k)
{
return T[k];
}
int main()
{
int a[] = {15,11,27,8,12};
int n = sizeof(a)/sizeof(a[0]);
int i,key,val;
table T[n];
table x;
for(i = 0; i < n; i++) {
T[i] = table(0,0);
key=i+1;
val=a[i];
INSERT(T,table(key,val));
x = SEARCH(T,1);
if (x.key == 0)
{
cout<<"No element inserted at the key "<< key <<endl;
} else {
cout<<"Element at key "<< key <<" is-> "<< x.val <<endl;
}
}
return 0;
}
解决方法
问题出在这条线上
x = SEARCH(T,1);
用1
替换key
x = SEARCH(T,key);
,
这里你已经传入了调用站点 INSERT(),1 as k 所以增量 您设置的 (key+=1) 不会被使用,并且永远不会搜索键 1 处的值。在迭代期间,它将继续搜索不存在的 k=1 处的值