私はnode = 0xddddddddのコードで問題を起こしています。私はルールの3つの問題にそれを絞り込んだとコピーコンストラクタを持っていないと思う。コピーコンストラクタを作成しようとしましたが、正しく実装しているかどうかはわかりません。基本的には、ノードを作成して、ベクトルに格納しているバイナリツリーオブジェクトに格納しています。コピーコンストラクタを作成する必要がありますか?ベクトルコピーの問題にバイナリツリーを格納していますか?
Environment.cpp
void Environment::evolve() {
std::cout << "> evolving function" << std::endl;
std::vector<Tree> popvec;
// Generate initial pop trees and store in vector
std::cout << "> generating initial population" << std::endl;
for (int i = 0; i <= Popsize-1; i++) {
Tree membertree(Maxdepth);
//popvec.push_back(membertree);
popvec.emplace_back(membertree);
} // <- A deconstructor is being called here that is causing the error
// If I understand right it is destructing the copy from putting it
// into the vector
Tree.cpp
// Constructor
Tree::Tree() {
root = NULL;
fitness = rand();
depth = 0;
}
// Overload constructor
Tree::Tree(int maxdepth) {
root = NULL;
fitness = rand();
depth = 0;
while (TreeDepth(root) < maxdepth) {
addNode(root);
}
}
// Copy constructor
Tree::Tree(const Tree &obj, int maxdepth) {
root = NULL;
fitness = obj.fitness;
depth = 0;
while (TreeDepth(root) < maxdepth) {
addNode(root);
}
}
// Destructor
Tree::~Tree() {
freeNode(root);
root = NULL;
}
// Post traversal node deletion
void Tree::freeNode(Node* node) {
if (node != NULL) {
freeNode(node->left); // This is where the error pops up
freeNode(node->right);
delete node;
}
}
// Adds a node to the tree
void Tree::addNode(Node* node) {
if (root == NULL) {
Node* temp = new Node();
root = temp;
}
else if (node->left == NULL) {
Node* temp = new Node();
node->left = temp;
}
else if (node->right == NULL) {
Node* temp = new Node();
node->right = temp;
}
else if (node->left != NULL) {
addNode(node->left);
}
else if (node->right != NULL) {
addNode(node->right);
}
}
編集:誰かがツリーの深さを求め
int Tree::TreeDepth(Node* node) {
if (node == NULL) {
return 0;
}
int nLeft = TreeDepth(node->left);
int nRight = TreeDepth(node->right);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
Node.cpp
Node::Node() {
functiontype = 0;
left = NULL;
right = NULL;
up = NULL;
}
// Do I need a copy constructor here as well?
Node::~Node() {
}
編集:私はこれをさらに得ているように見えるが、今、それはあなたが使用している場合は、ベクターに
// Copy constructor
Tree::Tree(const Tree& obj) {
fitness = obj.fitness;
depth = obj.depth;
if(obj.root == NULL){
root = NULL;
}
else {
copyTree(this->root, obj.root);
}
}
void Tree::copyTree(Node * thisRoot, Node * sourceRoot) {
if (sourceRoot == NULL)
{
thisRoot = NULL;
}
else
{
thisRoot = new Node;
thisRoot->left = sourceRoot->left;
thisRoot->right = sourceRoot->right;
copyTree(thisRoot->left, sourceRoot->left);
copyTree(thisRoot->right, sourceRoot->right);
}
}
私はそのコピーコンストラクタで実際に他の 'Tree'の' Node'sをコピーしていません。他のツリーのノードではなくルートノードを継続的に追加しているようです。 – user4581301
はい、それは良い点です。私はそのようなバイナリツリーをコピーする方法について実際にはわかりません。私はコピーされたものをたどることができます。うーん。 – MushinZero
合理的に聞こえる。 'obj'の' Node'のようなもの:新しい 'Node'を作成し、' newNode-> functiontype = objNode-> functiontype'を設定してから 'addNode(newNode)'を設定します。 – user4581301