c++ - 我的树节点缺少链接

标签 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;

}

最佳答案

Node::Add来电main更新 NodenodesStorage但不是 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)中,我们很少处理原始指针,newdelete运营商。相反,我们使用 std::shared_ptrstd::unique_ptr根据需要。 std::shared_ptr电话 delete在它的析构函数中没有其他std::shared_ptr引用同一个对象。这可确保资源在不再需要时自动处置(RAII 习语)。

关于c++ - 我的树节点缺少链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39049020/

相关文章:

c++ - 如何在Windows下编译Qt 4.6.3 for Windows Mobile (Windows CE)?

c++ - 我怎么知道我使用的是复制还是 move ?

c++ - 从先前的模板参数获取类型

python - 使用 ECMAScript 正则表达式验证 Python 列表索引语法

c++ - 语法帮助。模板函数对象中的模板运算符()

c++ - 将文本文件解析为对象时的错误处理

c++ - 使用 boost::future .then() 时出现编译错误

c++ - 如何在互斥锁中优先考虑特权线程?

c++ - 为信号槽绑定(bind)模板函数时使用占位符

c++ - memcpy -- 将 uint64 复制到 char *