【发布时间】:2021-05-06 16:39:42
【问题描述】:
这是我创建的类
#include <memory>
template <typename T>
class binary_tree {
private:
T t_data;
std::unique_ptr<binary_tree<T>> t_left, t_right;
class binary_tree_iterator { // -----------------------
private:
T data;
public:
binary_tree_iterator(T d) : data(d) {} // Iterator class
T& operator*() {return data;}
binary_tree_iterator& operator++() {} // <--------- ??????
};
// ------------------------
public:
binary_tree(T d) : t_data(d), t_left(nullptr), t_right(nullptr)
{}
void insert(T data) {
if(data <= t_data) {
if(t_left == nullptr) {
t_left = std::unique_ptr<binary_tree<T>>(new binary_tree<T>(data));
} else {
t_left->insert(data);
}
} else {
if(t_right == nullptr)
t_right = std::unique_ptr<binary_tree<T>>(new binary_tree<T>(data));
else
t_right->insert(data);
}
}
const T data() const {
return t_data;
}
const std::unique_ptr<binary_tree<T>>& left() const {
return t_left;
}
const std::unique_ptr<binary_tree<T>>& right() const {
return t_right;
}
binary_tree_iterator begin() {
if(t_left == nullptr) {
return binary_tree_iterator(t_data);
} else {
return t_left->begin();
}
}
binary_tree_iterator end() {
if(t_right == nullptr) {
return binary_tree_iterator(t_data);
} else {
return t_right->end();
}
}
};
我已经在我的容器类中声明了我的迭代器类。这可能是一个错误,但无论哪种方式,我都不确定如何定义我的重载增量函数。一旦我找到了 begin() 我就迷路了。似乎 unique_ptr() 是为单向指向而设计的。假设我必须以这种方式使用 unique_ptr,这里有一些工作吗?我曾考虑为 binary_tree 的每个实例提供一个头成员,该成员指向它的来源,但每个节点只能从其上方的节点访问。我做了某种索引,但这似乎完全违背了这种容器类型的目的。我正在解决练习,所以我只能使用 unique_ptr。
【问题讨论】:
-
unique_ptr 用于内存管理,而不是用于组织树。尝试使用普通指针!
-
使用 unique_ptr 表示具有 unique_ptr 的类“拥有”指向的对象,并负责删除它。这对于树节点对其子节点持有的指针(有些)有意义,对于您需要的父指针没有意义,因为子节点不拥有它的父节点(而是相反)。只需为此目的使用原始指针。
-
@U.W.
unique_ptr非常适合树中的子指针 -
@john 我需要 left() 和 right() 成员返回 unique_ptr ¯_(ツ)_/¯
-
@Joemoor94 现在这确实没有意义。如果您有名为
left()和right()的 getter 方法返回一个唯一指针,那么这意味着它们正在转移左子或右子的所有权(这没有意义),或者它们正在分配一个新的子节点并返回一个唯一的指向它的指针(这也没有意义)。
标签: c++ class c++11 iterator unique-ptr