微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将数组元素插入哈希表

如何解决将数组元素插入哈希表

我想编写一些代码,将数组中的元素插入下面的哈希表中。我将数组“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 处的值

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。