我正在审题 Tree Nodes Getting Lost并认为在 C++11 中这会是一个很好的练习。
我带来了下面的代码。但是 Root 元素没有连接到其余节点,我找不到原因。
编辑:您可以在此处找到代码:https://ideone.com/NCyRsx我使用 visual studio 但我得到了相同的结果。
#include <iostream>
#include <vector>
#include <array>
struct Node
{
int key;
std::vector<Node> children;
Node(int k)
{
key = k;
}
void Add(Node n)
{
children.push_back(n);
}
void display()
{
std::cout << "My value is " << key << std::endl;
std::cout << "My " << children.size() << " kid(s) are : " << std::endl;
for( auto n : children)
{
n.display();
}
}
};
int main()
{
constexpr int numNode = 5; // for
std::array<int, numNode> numbers = { 4, -1, 4, 1, 1 };
std::vector<Node> nodesStorage;
for (int i = 0 ; i < numNode ; i++)
{
nodesStorage.push_back(Node(i));
}
nodesStorage.push_back(Node(-1));
for (int i = 0 ; i< numNode ; i++)
{
if(numbers[i] == -1) // the root
{
nodesStorage[numNode].Add(nodesStorage[i]);
}
else
{
nodesStorage[numbers[i]].Add(nodesStorage[i]);
}
}
nodesStorage[1].display();
nodesStorage[numNode].display();
return 0;
}
最佳答案
Node::Add
来电main
更新 Node
在nodesStorage
但不是 Node::children
(反之亦然)因为 Node
s 按值传递(即复制)。正如评论中指出的那样,您必须使用指针而不是值。
替换
std::vector<Node> nodesStorage;
通过
std::vector<std::shared_ptr<Node>> nodesStorage;
并修复你的编译器提示的所有其他地方。哦,确保你#include <memory>
.
由于您将此作为练习进行,因此我暂时不进行详细的修复。以下是 std::shared_ptr
的引用资料和 std::make_shared
.
在 C++11(或者说 C++14)中,我们很少处理原始指针,new
或 delete
运营商。相反,我们使用 std::shared_ptr
或 std::unique_ptr
根据需要。 std::shared_ptr
电话 delete
在它的析构函数中没有其他std::shared_ptr
引用同一个对象。这可确保资源在不再需要时自动处置(RAII 习语)。
关于c++ - 我的树节点缺少链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39049020/