【发布时间】:2016-02-22 06:09:52
【问题描述】:
所以我目前有一个简单的结构(链表),我将在 HashMap 中使用它:
struct Node {
std::string key, value;
Node* head;
}
我目前正在尝试使用指向每个结构的指针动态分配一个数组。这就是我现在所拥有的......
Node* nodes = new Node[100]
我知道这会将一个包含 100 个节点的数组分配到内存中(稍后我将不得不删除它);但是,在迭代时尝试遍历这些节点(我将其实现为链表)...
for (int x = 0; x < 100; x++) {
Node current = nodes[x]; // Problem is I wanted an array to node pointers. This is not a pointer.
while (current != nullptr) { // this isn't even legal since current is not a pointer.
// DO STUFF HERE
current = current.next; // This is not a pointer access to a method. I'm looking to access next with current->next;
}
}
希望我已经足够清楚了。有人可以如何分配指向结构的动态指针数组吗?到目前为止,我能够动态分配一个结构数组,而不是一个指向结构的指针数组。
【问题讨论】:
-
基本上,通过为您的节点提供连续内存,您正在破坏整个链接列表的想法。不需要下一个节点,因为您有空间信息(即索引)
-
您似乎不确定是要链表还是动态数组。
-
我的想法是我正在实现一个 hashmap,因此需要一个动态分配的 LinkedLists 数组。
-
@Xari 这清楚了,你应该编辑你的问题。并且请不要在 cmets 中描述问题,没有人阅读 cmets :)
-
完成。谢谢你提醒我。我只是偶然发现了这个声明...... Node** nodes = new Node*[100],它显然创建了一个带有指向我的节点的指针的动态数组。这是正确的吗?
标签: c++ arrays pointers struct