【问题标题】:Return reference from binary search tree C++ [closed]从二叉搜索树C++返回引用[关闭]
【发布时间】:2015-08-22 13:59:12
【问题描述】:

在我的二叉搜索树中考虑以下搜索函数。

template <class elemType>
elemType& BSTree<elemType>::search(const elemType & searchItem) const
{
    std::cout << "in 1st teir search" << std::endl;
    if (root == NULL)
    {
        std::cout << "Tree is empty, and there for no data will be in this tree." << std::endl;
    }
    else
    {
        std::cout << "Entering 2nd teir search" << std::endl;
        return search(root, searchItem);
    } //End else
} //End search(1param)

template <class elemType>
elemType& BSTree<elemType>::search(nodeType<elemType>* node, const elemType& dataToFind) const
{
    elemType found;

    if (node == NULL)
    {
        std::cout << "Not found. Node is null." << std::endl;
    }
    else
    {
        if (node->data == dataToFind)
        {
            std::cout << "Data found" << std::endl;
            found = node->data;
        }
        else if (node->data < dataToFind)
        {
            std::cout << "Data not found, searching to the RIGHT" << std::endl;
            found = search(node->rLink, dataToFind);
        }
        else
        {
            std::cout << "Data not found, searching to the LEFT" << std::endl;
            found = search(node->lLink, dataToFind);
        }
    } //End else
    return found;
} //End search(2param)

每当我访问/搜索不是根目录的数据时,当我去分配该数据时,我的程序就会崩溃。

我错过了什么?

注意:请理解,也许我可以在遍历中使用函数指针来执行返回值,但出于我使用树进行搜索的目的,将返回对对象的引用。

【问题讨论】:

  • 离题:在search 的第一个版本中,您的if 路径不返回任何内容或抛出。用nullptr 初始化elemType found; 是个好主意。

标签: c++ search recursion binary-search-tree


【解决方案1】:

您返回的不是对您要查找的节点的引用,而是对found 的引用,该引用具有自动存储功能,并在函数退出时被销毁。

要解决此问题,您可以将found 设为指针,将节点的地址存储在其中,然后将return *found; 放在函数末尾。

【讨论】:

  • 那么这两个函数都会返回一个指针还是只返回第二层?我相信我之前尝试过,并且从 'Type' 的右值中得到了“类型为 'Type&' 的非常量引用的无效初始化”
  • 你可以让它们都返回引用,只需在内部使用一个指针,这样你就可以更新它。
  • 事实上,你最好返回一个指针,这样你就可以表示你找不到节点的情况。
  • 首先,感谢您的帮助。其次,对不起,我是个菜鸟。所以我所做的只是发现现在是一个指针,我从我的 tier2 函数返回一个指针,但是当我到达分配 found ie found = node->data; 的任何行时找到 = 搜索(节点-> rLink,dataToFind);找到 = 搜索(节点->lLink,dataToFind);我收到此错误:错误:无法在分配中将 'Unit' 转换为 'Unit*'| (注意单位是用户定义的数据类型)
  • 这不是你使用指针的方式。您需要分配您要指向的对象的地址,例如found = &amp;node-&gt;data;
猜你喜欢
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多