假设您有一个结构(简称为Node),其中包含一个字符串Content和一个向量(Node *)子级。
假设子字符串是父字符串的函数,因此您需要使用递归方法来生成子节点并将其链接到父节点。
什么是有效的方法?我目前的方法是:
void Node::branch(vector<vector<Node>> &generations) {
string child; //this will be the content of the child Node
int generation_i = 0 //index of vector in which child Node will be stored (this vector is one of the 'generations' in generations)
child = make_substring(content); //returns a child string based on content
generations[generation_i].emplace_back(child); //make a child Node in generation
child.branch(generations); //recursion
adopt(generations[generation_i][generations[generation_i].size() - 1]); //store (address of child Node) in children
但是,当我执行该代码时,节点的所有子节点都具有相同的内容和地址,这表明adopt()
将附加所传递的地址,并用已传递的地址替换已经存在的每个地址。
void Node::adopt(Node child) { children.push_back(&child); }//append [address of child] to children [vector of pointers to children]