1

在树中,在获取输入(takeInput函数内部)时,树节点是使用动态分配创建的,但我尝试静态地进行,但是由于树节点是在本地函数内声明的,它应该不起作用,因为它是一个局部变量(我期待一个错误)。但是为什么即使在那之后我也可以打印它:

注意:此代码以递归方式接受输入(可能不是最好的方法)

#include<bits/stdc++.h>
using namespace std;
template <typename T>
class treeNode{
    public:
    T data;
    vector <treeNode<T>> children;
    treeNode(T data){
        this->data=data;
    } 
};
treeNode<int> takeInput(){
    int rootdata;
    cout<<"Enter Node"<<endl;
    cin>>rootdata;
    // treeNode<int>* root= new treeNode<int>(rootdata);

    treeNode<int> root(rootdata);   //Static Allocation

    cout<< "Enter Number of children of "<<rootdata<<endl;
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        treeNode<int> child = takeInput();
        root.children.push_back(child);
    }
    return root;
}
void printTree(treeNode<int> root){
    cout<<root.data<<": ";
    for(int i=0;i<root.children.size();i++){
        cout<<root.children[i].data<<",";
    }
    cout<<endl;
    for(int i=0; i<root.children.size();i++){
        printTree(root.children[i]);
    }
}
int main(){
    treeNode<int> root= takeInput();
    printTree(root);
    return 0;
}

以下代码使用动态分配:

#include<bits/stdc++.h>
using namespace std;

template <typename T>
class TreeNode{
    public:
    T data;
    vector <TreeNode<T>*> children;
    TreeNode(T data){
        this->data=data;
    }
};
TreeNode<int>* takeInput(){
    int rootdata;
    cout<<"Enter node"<<endl;
    cin>>rootdata;
    TreeNode<int>* root=new TreeNode<int>(rootdata);
    cout<<"Enter number of children of "<<rootdata<<endl;
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        TreeNode<int>* child=takeInput();
        root->children.push_back(child);
    }
    return root;
}
void printTree(TreeNode<int>* root){
    if (root == NULL){
        return;
    }
    cout<< root->data<<" :";
    for(int i=0;i<root->children.size(); i++){
        cout<<root->children[i]->data<<",";
    }
    cout<<endl;
    for(int i=0;i<(*root).children.size();i++){
        printTree(root->children[i]);
    }
}
int main(){
    TreeNode<int>* root = takeInput();
    printTree(root);
    return 0;
}
4

1 回答 1

1

您的代码相当于

A foo() {
    A a;
    a = bar();
    return a;
}

a只是复制到返回值中(也可以避免该复制)。替换AtreeNode<int>,语义保持不变。

那么为什么是动态代码呢?

我猜使用动态分配的代码版本可能被编码为类似

struct A {
    std::vector<A> vecA;
};

是一个递归定义,A因为vecA声明A的时间是不完整的类型。但现在情况不再如此,这已正式进入C++17(尽管它在早期版本中也适用于某些编译器),其中一些 STL 容器可以处理不完整的类型。因此它使用了表格

vector <TreeNode<T>*> children;

存储指向子节点的指针和代码,类似于熟悉的 LinkedList 节点数据结构定义

struct Node {
    int data;
    Node* next; // The TreeNode stores a vector of pointers instead.
};

结论

堆栈分配通常是首选因为它比堆路由更快。此外,除非使用智能指针,否则具有动态分配的代码会带来内存管理的麻烦。您的代码不需要它。为您的示例选择堆栈分配路线,并让我们std::vector负责维护动态数组。

于 2021-07-31T13:38:47.207 回答