从二叉搜索树C++返回引用
Return reference from binary search tree C++
考虑我的二叉搜索树中的以下搜索函数。
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)
每当我访问/搜索不是root的数据时,当我去分配该数据时,我的程序就会崩溃。
我错过了什么?
注意:理解也许我可以在遍历中使用函数指针来返回值,但出于目的,我使用我的树进行搜索将返回对对象的引用。
您不会返回对要查找的节点的引用,而是返回对 found
的引用,该引用具有自动存储功能,并在函数退出时销毁。
要解决此问题,您可以将found
设置为指针,将节点的地址存储在其中,然后在函数末尾return *found;
。
相关文章:
- 寿命延长从函数返回引用
- 了解C++如何返回引用并绑定到引用
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 从类返回引用向量
- 使用unique_ptr并返回引用,或者我应该使用shared_ptr并在需要时制作副本
- 混淆C++从函数返回引用
- 两个相同的重载运算符[]一个返回引用
- 为什么向量的.at()成员函数返回引用而不是迭代器
- C++使用和返回引用
- 返回 T 引用的 Const 函子禁止赋值
- 返回引用是否也会延长其生存期?
- 如何返回引用,然后递增迭代器
- 如果使用返回引用的函数初始化"auto"var,为什么它不声明引用类型?
- 我是否需要将 ref 与 make_pair 一起使用才能返回引用?
- 在 vector::at 返回引用后进行更改
- 为什么PyImport_ImportModule返回引用计数为 3 而不是 1 的 PyObject*
- 超出返回引用的单一实例生存期
- Boost.Python 返回引用现有 c++ 对象的 python 对象
- C++ 运算符 += 重载返回引用
- 如何声明接受转发引用并返回引用或副本的函数模板