I am writing a deep constructor copy function for a directed graph:
class Graph {
class Node {
private:
std::vector<Node*> childs;
public:
Node* clone() {
Node* n = new Node(*this);
for(int i = 0; i < node->childs.size(); i++) {
n->addChild(childs[i]->clone());
}
return n;
}
};
Graph(const Graph& h) {
root = h.root->clone();
}
private:
Node* root;
};
The copy constructor works if I have a tree, but it fails for the following case as it creates two separate clones of B. How do I fix the problem? Do I need to move to the adjacency list representation?
A
|\
|/
B
addChild, it looks like your clones have twice as many children as they should.