我的树节点缺少一个链接



我正在浏览树节点丢失的问题,并认为这将是c++11中一个很好的练习。

我带来了下面的代码。但是根元素没有连接到其他节点,我找不到原因。

编辑:你可以在这里找到代码: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;
}

main中的Node::Add调用更新nodesStorage中的Node s,但不更新Node::children(反之亦然),因为Node s是按值传递的(即复制)。正如在注释中指出的那样,您必须使用指针而不是值。

代替

std::vector<Node> nodesStorage;

std::vector<std::shared_ptr<Node>> nodesStorage;

并修复编译器抱怨的其他地方。哦,确保你是#include <memory> .

由于您将此操作作为练习,因此我现在省略了详细的修复。以下是std::shared_ptrstd::make_shared的参考。

在c++ 11(或者更确切地说是c++ 14)中,我们很少处理原始指针、newdelete操作符。相反,我们根据需要使用std::shared_ptrstd::unique_ptr。当没有其他std::shared_ptr引用同一对象时,std::shared_ptr在其析构函数中调用delete。这确保了资源在不再需要时被自动处置(RAII习惯用法)。

最新更新