实现我自己的二进制树
Implementing my own binary tree
对于家庭作业,我必须实现一个二进制树(不使用STL二进制树)容器。除了一个外,我所有的树函数都在工作。
链接到我的代码:https://github.com/matthamil/BinaryTree
在bt_class.h中,我有一个带有模板实现的binary_tree模板类。
在bintree.h中,我有一个带有模板实现的binary_tree_node类。
在main.cpp中,我进行了一系列测试来确保函数正常工作。
我的问题在这里:
template <class Item>
Item binary_tree<Item>::retrieve( ) const
{
return current_ptr->data();
}
我需要这个函数的返回类型是存储在binary_tree_node中的任何内容的数据类型。我不知道如何做到这一点。
对于当前实现,它返回一个指向当前节点的指针。
我应该能写
cout << test->retrieve();
在main.cpp中,输出将是当前节点的数据。然而,由于它返回了一个指针,我必须添加一个额外的步骤:
*first = test->retrieve();
cout << first->data() << endl;
//"first"
有人能帮忙吗?
我认为问题就在这里,add_left,add_right。
template <class Item>
void binary_tree<Item>::create_first_node(const Item& entry)
{
if (count == 0)
{
root_ptr = new Item(entry);
current_ptr = root_ptr;
count++;
} else {
std::cout << "Can't create first node for tree that has a first node already." << std::endl;
}
}
这里发生的情况是,您正在传递节点的指针并调用new。所以基本上你要做的是创建一个binary_tree_node(&binary_tree _node)。
binary_tree_node<string> *first = new binary_tree_node<string> ("first");
binary_tree_node<string> *second = new binary_tree_node<string> ("second");
binary_tree_node<string> *third = new binary_tree_node<string> ("third");
test->create_first_node(*first);
test->add_right(*second);
test->add_left(*third);
因此,在您的binary_tree_node中还有另一个binary_tee_node。有不同的方法可以修复它。修复它的最佳方法只是将指针分配给current_ptr,或者简单地在binary_tree_node中实现一个适当的复制构造函数。然而,正如评论已经解释的那样,这是一个糟糕的设计选择。类binary_tree应该在内部生成binary_tree_node类,而用户不必手动实例化这些类并处理这些指针。
相关文章:
- 没有为自己的结构调用列表推回方法
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- C++从对象自己的类中删除对象
- 使用 std::optional,而不是自己的结构
- 子轴围绕父轴而不是他自己的轴旋转
- C++用于从流中读取二进制值的任何标准库
- 消除好友和成员二进制运算符的歧义
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 长双精度C++是IEEE二进制128的实现吗?
- 二进制搜索的终止点
- uint8_t同一二进制文件的不同十进制值
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- 二进制表达式的操作数无效 - 使用 for 和迭代器
- 重载 + 自己的类和 std::string 的运算符
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 自己的C++网络协议:如何定义唯一的二进制报文值
- C++ 集<>类对象。使用自己的比较器给出错误:C2804:二进制'operator <'参数过多
- 实现我自己的二进制树