转换错误无效且类型无效

时间:2017-04-10 11:15:12

标签: c++ data-structures hash

问题:

  

编写一个在student roll no上实现哈希函数的程序,并在它们的系列中对它们进行分类。与5000423一样,最后2位数字23,2 + 3 = 5,所以属于5。

我的尝试:

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;

const int tablesize= 20;

class hashentry
{
public:
    int key;
    int value;

    hashentry(int key,int value)
    {
        this->key=key;
        this->value=value;
    }
};

class hashmap
{
public:
    hashentry **table;
public:
    hashmap()
    {
        int table=new hashentry *[tablesize];
        for(int i=0;i<tablesize;i++)
        {
            table[i]=NULL;
        }
    }

    int hashfunc(int key)
    {
        return key%tablesize;
    }

    void insert(int key, int value)
    {
        int hash=hashfunc(key);
        while(table[hash]!=NULL && table[hash]->key!=key)
        {
            hash=hashfunc(hash+1);
        }
        table[hash]=new hashentry(key,value);
    }
};

int main()
{
    int key;
    int value;
    hashmap hash;
    cout<<"enter value";
    cin>>value;
    cout<<"enter key at which element is to be inserted";
    cin>>key;
    hash.insert(key,value);
    return 0;
}

捕获的错误:

In constructor 'hashmap::hashmap()':
invalid conversion from 'hashentry**' to 'int'
invalid types 'int[int]' for array subscript

1 个答案:

答案 0 :(得分:1)

int table=new hashentry *[tablesize];

new hashentry *[tablesize]的返回类型为hashentry**。由于您尝试将其分配给int变量,编译器会抱怨。您可能想要省略int,因为您已经使用正确的类型定义了同名的成员变量,例如写

table = new hashentry *[tablesize];

应该这样做。