如何解决使用 unique_ptr<T> 使我的二叉树类可迭代
我想让我的类对这个函数可迭代(假设我不能改变这个)
// basically my class wrapped in a unique_ptr
using tree_ptr = typename std::unique_ptr<binary_search_tree::binary_tree<T>>;
// then passed as a reference to this tester function along with a the correct sequence
static void test_sort(const tree_ptr<T> &tree,const std::vector<T> &expected)
{
std::vector<T> actual;
for (auto& x : *tree) {
actual.push_back(x);
}
REQUIRE(expected == actual);
}
这是我在命名空间 binary_search_tree 中创建的类
namespace binary_search_tree {
template <typename T>
class binary_tree {
private:
T t_data,min;
std::unique_ptr<binary_tree<T>> t_left,t_right;
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;
}
// const std::unique_ptr<binary_tree<T>>& begin() const {
//
// std::unique_ptr<binary_tree<T>>& leaf = this;
// while(leaf) {
// leaf = leaf->left();
// }
// return leaf;
// }
// const std::unique_ptr<binary_tree<T>>& end() const {
// return this;
// }
//
// bool operator!=(const leaf &rhs) {
// return this;
// }
//
// bool operator*(const leaf &rhs) {
// return this;
// }
};
} // namespace binary_search_tree
begin() 应该继续调用 left() 直到它到达一个 nullptr,而 end() 应该对 right() 做同样的事情。我对这些函数应该返回什么感到困惑。我知道我还需要在某个时候定义一个增量器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。