c++ - 无效转换错误和无效类型

标签 c++ data-structures hash

<分区>

问题:

Write a program that implements a hash function on student roll no and categorize them in their families. Like 5000423, last 2 digits 23, 2+3=5, so belongs to family 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

最佳答案

int table=new hashentry *[tablesize];

new hashentry *[tablesize] 的返回类型是hashentry**。由于您试图将其分配给 int 变量,因此编译器会提示。可能,您打算省略 int,因为您已经定义了具有正确类型的同名成员变量,例如写作

table = new hashentry *[tablesize];

应该可以解决问题。

关于c++ - 无效转换错误和无效类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43321726/

相关文章:

c++ - 类模板链接器错误

c++ - 查找后缀到前缀表达式

c - 实现 infixToPostfix 方法,但不知道为什么我第一次推送 '('

哈希函数来索引相似的文本

c++ - std::unordered_set 指针

c++ - 将 bool 转换为位域中的位

C++ - Brent-Pollard rho 算法无限循环

c++ - 在 MFC 组合框中设置文本而不将其添加到列表中

java - 根据按钮按下选择数组存储的内容

function - 在布隆过滤器中使用哪些哈希函数