【问题标题】:Binary Tree Assignment Operator Overload Problem C++二叉树赋值运算符重载问题 C++
【发布时间】:2019-08-09 09:17:48
【问题描述】:

我正在尝试为我的二叉搜索树重载赋值运算符。

Example: tree1 = tree2 

我想删除 tree1 中的所有节点,并深拷贝 tree1 中的所有节点。

我已经有函数了:

Node* deepCopyTree(const Node *source)

效果很好。我也创建了这个函数:

void deleteTree(Node* root)
{
    if (root)
    {
        deleteTree(root->left);
        deleteTree(root->right);
        delete root;
    }
}

当我看到我的调试它工作。运算符重载函数:

    BST& BST::operator=(const BST &rhs) 
{
    DestroyRecursive(root);
    deepCopyTree(rhs.root);
    return *this;

}

这在复制时会引发错误。我为此工作了 10 个小时,这是我留下的最小的东西,我想完成它。请帮忙:)。

这是我的深拷贝构造函数:

BST::BST(const bST&rhs)
    :root(deepCopyTree(rhs.root))
{
}

deepCopyTree 返回节点*

struct Node
{
    std::string value = "";
    Node *left = nullptr;
    Node *right = nullptr;
};

解构器:

BST::~BST()
{
    DeleteTree(this->root);
}

void DeleteTree(Node* root)
{
    if (root)
    {
        DeleteTree(root->left);
        DeleteTree(root->right);
        delete root;
    }
}

【问题讨论】:

  • 忠告 -- 先实现复制构造函数,而不是实现赋值运算符。一旦你这样做了,赋值运算符就可以通过使用copy / swap idiom 变得微不足道了。如果您已经实现了复制构造函数,请发布它,因为它可能会导致您使用上述成语寻找答案。
  • @PaulMcKenzie 是的我已经实现了我现在发布它
  • BST tree1; BST tree2 = tree1; -- 首先让它工作(实现复制构造函数)。一旦你完成了这项工作,你花费的 10 个小时将减少到 5 分钟来实现赋值运算符(可能不到 5 分钟)。
  • 您还需要发布 BST 类声明,以查看其他成员变量是什么(除了root)。
  • 好的,那么root 是 BST 中唯一的成员变量吗?此外,您需要一个有效的 BST 析构函数。你有吗?

标签: c++ operator-overloading binary-tree assignment-operator


【解决方案1】:

如果BST 的复制构造函数和析构函数正常工作(并且复制构造函数不使用赋值运算符),则可以使用copy/swap idiom 轻松编写BST 赋值运算符:

#include <algorithm>
//...
BST& BST::operator=(const BST &rhs) 
{
    if ( &rhs != this )  // for optimization purposes, check for self assignment
    {
        BST temp(rhs);  // copy the rhs (uses copy constructor)
        std::swap(temp.root, root);  // swap out the members (root with temp.root)
    } // temp now dies off with the old data (uses destructor)
    return *this;   
} 

请注意,我们所做的只是创建一个临时的(这就是复制构造函数必须正常工作的原因)。然后将this 成员替换为临时成员。一旦完成,当temp 被销毁时,它会带走旧数据(这就是析构函数必须正常工作的原因)。

如果有更多成员,那么您也需要将它们换掉(我假设BST 中唯一的成员变量是root)。

【讨论】:

  • 所以你基本上有了解决方案,只是你没有意识到它(花了 10 个小时收效甚微)。
猜你喜欢
  • 2023-03-07
  • 2013-11-21
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 2013-03-30
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多