【问题标题】:Insert elements of array into hash table将数组元素插入哈希表
【发布时间】:2021-01-02 13:07:28
【问题描述】:

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

【问题讨论】:

    标签: c++ arrays hashtable


    【解决方案1】:

    这行有问题

    x = SEARCH(T, 1);
    

    1 替换为key

    x = SEARCH(T, key);
    

    【讨论】:

      【解决方案2】:

      这里你已经传入调用站点 INSERT(), 1 as k 所以增量 您设置的 (key+=1) 将不会被使用,并且永远不会搜索键 1 处的值。在迭代期间,它将继续搜索不存在的 k=1 处的值

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-16
        • 2010-10-24
        • 2015-06-25
        • 2017-03-28
        相关资源
        最近更新 更多