我的树节点缺少链接

时间:2016-08-19 23:35:53

标签: c++ c++11

我正在审问问题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;

}

1 个答案:

答案 0 :(得分:3)

Node::AddmainNodenodesStorageNode::childrenNodestd::vector<Node> nodesStorage; std::vector<std::shared_ptr<Node>> nodesStorage; #include <memory>次呼叫new按值(即复制)。正如评论中指出的那样,你必须使用指针而不是值。

替换

delete

通过

std::shared_ptr

并修复编译器抱怨的其他任何地方。哦,确保你std::unique_ptr

由于你这样做是为了练习,我现在暂时没有详细解决。以下是std::shared_ptrstd::make_shared的参考资料。

在C ++ 11(或更确切地说是C ++ 14)中,我们很少处理原始指针,std::shared_ptrdelete运算符。相反,我们会根据需要使用std::shared_ptrfloat:left。当没有其他float:right引用同一个对象时,.container { display: inline-block; text-align: center; width: 100%; position: relative; } .left, .middle, .right { width: 200px; height: 200px; background-color: red; display: inline-block; } .left { float: left; } .right { float: right; }会在其析构函数中调用<div class="container"> <div class="left"> <div class="content"> </div> </div> <div class="middle"> <div class="content"> </div> </div> <div class="right"> <div class="content"> </div> </div> </div>。这可确保资源在不再需要时自动处理(RAII习语)。