Предположим, у вас есть структура (давайте назовем ее Node), содержащая строку Content и вектор (Node *) Children.
Предположим, что дочерняя строка является функцией родительской строки, поэтому вынеобходимо использовать рекурсивный метод для генерации и связывания дочерних узлов с родительскими узлами.
Каким был бы эффективный способ сделать это?Мой текущий подход:
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]