[英]Initializing an array of structs within a class definition
I have a struct that creates nodes for a BST like this我有一个结构可以为这样的 BST 创建节点
struct BSTNode{
int data;
BSTNode *left;
BSTNode *right;
};
and I need to create an array of these root nodes inside of a class我需要在类中创建这些根节点的数组
class HashBST{
public:
bool lookup(int);
void insert(int);
bool remove(int);
float getLoad();
//private:
int hash(int);
BSTNode *table[1019];
float load;
int occupied = 0;
int tableSize = 1019;
};
from there I want to be able to check and see if a BST node has an entry or not.从那里我希望能够检查并查看 BST 节点是否有条目。 Initially I tried setting the
data
int to -1 in the struct definition, but in my array in the class, each node had a garbage data value.最初我尝试在结构定义中将
data
int 设置为 -1,但是在我的类中的数组中,每个节点都有一个垃圾数据值。
Is there a way to set all of the data values to -1, or more ideally, set all the pointers in the table
array to NULL
until something is stored in them?有没有办法将所有数据值设置为 -1,或者更理想的是,将
table
数组中的所有指针设置为NULL
直到其中存储了某些内容?
Is there a way to set all of the data values to -1,
有没有办法将所有数据值设置为 -1,
There isn't because the design of your node implies a specific design of the hash table.没有,因为您的节点的设计意味着哈希表的特定设计。 Since you have nodes, that implies that you use separate chaining for hash table collision resolution.
由于您有节点,这意味着您使用单独的链接来解决哈希表冲突。
And that means your bucket array table
needs to be initialized with null pointers, otherwise it contains indeterminate values:这意味着您的存储桶数组
table
需要用空指针初始化,否则它包含不确定的值:
BSTNode* table[1019] = {}; // Zero-initialize buckets.
And then lookup
member function is going to look like:然后
lookup
成员函数将如下所示:
bool HashBST::lookup(int value) {
unsigned value_hash = hash(value); // Hash must be an unsigned value.
unsigned index = value_hash % tableSize;
for(BSTNode* node = table[index]; node; node = node->right) {
if(node->data == value)
return true;
}
return false;
}
In a more advanced version the bucket table should be just a pointer BSTNode* table;
在更高级的版本中,bucket 表应该只是一个指针
BSTNode* table;
which gets initialized with the result of new[]
and the size of the referred table is in tableSize
.它使用
new[]
的结果进行初始化,引用表的大小在tableSize
。
Here is how I would do it in a C++ friendly way:这是我将如何以 C++ 友好的方式做到这一点:
Firstly, convert table
to std::vector
:首先,将
table
转换为std::vector
:
std::vector<BSTNode*> table
Create a constructor for HashBst
that initializes your std::vector<T*>
with all nullptr values.为
HashBst
创建一个构造函数,用所有 nullptr 值初始化std::vector<T*>
。
HashBST() : table(1019) {} //table items are all nullptr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.