【发布时间】:2021-05-09 08:39:45
【问题描述】:
我想通过引用访问我的迭代器类
#include <iostream>
template <typename T> class binary_tree;
template <typename T>
class binary_tree_iterator {
private:
binary_tree<T>* tree;
T data;
public:
binary_tree_iterator(binary_tree<T>* t) : tree(t) {}
T& operator*() {data = tree->data(); return data;}
binary_tree_iterator& operator++() {tree = tree->get_node(); return *this;}
bool operator!=(binary_tree_iterator& rhs) {return tree->data() != rhs.tree->data();}
};
template <typename T>
class binary_tree {
private:
T t_data;
binary_tree<T>* node;
binary_tree_iterator<T>* It;
public:
binary_tree(T d) : t_data(d), node(nullptr), It(nullptr)
{}
T& data() {
return t_data;
}
void set_node(binary_tree<T>* node) {
this->node = node;
}
binary_tree<T>* get_node() {
return node;
}
binary_tree_iterator<T> begin() {
It = new binary_tree_iterator<T>(this);
return *It;
}
binary_tree_iterator<T> end() {
if(node == nullptr) {
It = new binary_tree_iterator<T>(this);
return *It;
} else {
return node->end();
}
}
};
int main() {
binary_tree<int>* tree = new binary_tree<int>(2);
tree->set_node(new binary_tree<int>(3));
//for(auto& x: *tree) <--- does not work
for(auto x: *tree) {
std::cout << x << std::endl;
}
}
我想在其中使用它的 for-range 循环类似于 for(auto& x: *tree)。我如何给它一个参考?创建迭代器时是否有这样做的标准方法?当我返回数据值时,我将它分配给迭代器数据成员,以便我可以通过引用返回。我必须对我的迭代器做同样的事情吗?我不认为这是执行此操作的标准方式。
【问题讨论】:
-
在
for(auto& x: *tree)x中是对binary_tree中当前数据节点的引用,而不是迭代器。有关基于范围的 for 循环扩展的伪代码,请参见此处 en.cppreference.com/w/cpp/language/range-for -
迭代器是轻量级和可复制的。 很少您应该持有对迭代器的引用。顺便说一句,你的树的
begin和end迭代器是相同的,所以在迭代循环期间,你的binary_tree_iterator::operator++怎么知道它何时到达树的末尾? -
@Remy 怎么样?
-
@Joemoor94 怎么样?请更具体。
标签: c++ class iterator containers