C++ hashnode构造函数如何初始化
我正在尝试使用分离链实现哈希。我无法理解C++ hashnode构造函数如何初始化,c++,constructor,C++,Constructor,我正在尝试使用分离链实现哈希。我无法理解hashnode构造函数是如何初始化的,尽管我们只是为类hashmap构造对象。它们都是彼此私有的,而且我没有从hashnode派生类hashmap。那这是怎么回事 #include <iostream> using namespace std; static const int table_size = 10; class hashnode { public: int key;
hashnode
构造函数是如何初始化的,尽管我们只是为类hashmap
构造对象。它们都是彼此私有的,而且我没有从hashnode
派生类hashmap
。那这是怎么回事
#include <iostream>
using namespace std;
static const int table_size = 10;
class hashnode {
public:
int key;
int value;
hashnode* next;
hashnode(int key, int value)
{
this->key = key;
this->value = value;
this->next = NULL;
}
};
class hashmap {
hashnode** table;
public:
hashmap()
{
table = new hashnode* [table_size];
for(int i=0;i<table_size;i++)
{
table[i] = NULL;
}
}
int hash(int key)
{
return key%table_size;
}
void insert(int key, int value)
{
int hash_val = hash(key);
hashnode* prev = NULL;
hashnode* entry = table[hash_val];
while(entry != NULL)
{
prev = entry;
entry = entry->next;
}
if(entry == NULL)
{
entry = new hashnode(key,value);
if(prev == NULL)
{
table[hash_val] = entry;
}
else
{
prev->next = entry;
}
}
else
{
entry->value = value;
}
}
void printtable(int key)
{
while(table[0] != NULL)
{
cout<<table[0]->key<<endl;
table[0] = table[0]->next;
}
}
};
int main()
{
hashmap hash1;
int key,value;
int choice;
#包括
使用名称空间std;
静态常数int table_size=10;
类hashnode{
公众:
int键;
int值;
hashnode*next;
hashnode(int键,int值)
{
这个->键=键;
这个->值=值;
此->下一步=空;
}
};
类哈希映射{
hashnode**表;
公众:
hashmap()
{
table=新hashnode*[table_size];
对于(int i=0;不精确;
}
if(条目==NULL)
{
entry=新的hashnode(键、值);
if(prev==NULL)
{
表[hash_val]=条目;
}
其他的
{
上一步->下一步=输入;
}
}
其他的
{
输入->值=值;
}
}
无效打印表(int键)
{
while(表[0]!=NULL)
{
cout行table=newhashnode*[table_size];
正在调用hashnode
的构造函数。这就是new
所做的;它为每个对象分配空间,然后调用对象的构造函数
您要求编译器创建10个(基于表大小)hashnode
对象。如果“数组”hashmap::table
有一个固定的编译时大小,为什么不使用一个实际的数组呢?如果这个大小实际上不是一个编译时常量,那么您可能应该使用std::vector
。@JoachimPileborg可能是因为这个东西最终会通过学术界驱动的任务进行扩展,一旦加载因子为e,所有内容都会重新刷新太好了。至少这就是我这么做的原因。(好吧,那是个谎言,我会像我怀疑的几乎所有其他人一样使用std::unordered_map
)。至于你的问题,我真的不太明白。hashnode
类只有public
成员(几乎使它成为结构体
),因此在任何地方创建它的实例都没有问题。hashnode
类没有任何对hashmap
类的引用。您确实创建了hashnode
类的实例,并通过在执行新建hashnode(..)时(间接)调用构造函数来初始化这些实例
@JoachimPileborg如果你能帮助我更好的实现,那将是一个很大的帮助。他说的是你的陈述“我们只为类hashmap构造对象”是不正确的。你认为新hashnode(键、值)怎么样
确实,如果不动态分配和构造一个新的hasnode
?并且关于替代实现,您的插入
成员可以是。