迭代器模式用来处理复杂数据结构中的遍历问题,主要包括实现++、!=运算符,可以用来比较迭代器
实现代码
template<typename T>struct Node {
T value;
Node<T>* left{ nullptr };
Node<T>* right{ nullptr };
Node<T>* parent{ nullptr };
};
template<typename U>
struct ProOrderIterator {
Node<U>* current;
explicit PreOrderIterator(Node<U>* current) :current{ current } {}
Pre0rderIterator<U>& operator++() {
if (current->right) { //如果存在右节点
current = current->right; //首先找到右节点
while (current->left) //然后找到最左侧的节点
current = current->left;
}
else {
Node<T>* p = current->parent; //,没有右节点则回到父节点
while (p && current == p->right) //刚才遍历的是父节点的右节点 ,则一直向上
{
current = p;
p=p->parent
}
current = p; //直到找到一个节点是父节点的左节点,返回父节点
}
return*this;
}
bool operator!=(const PreOrderIterator<U>& other) {
return current != other.current;
}
Node<U> operator*() { return *current; }
};
这段代码实现了一个二叉树的迭代器(其他代码省略)
我们可以看到重载了++、!=、*运算符。
总结
迭代器在编程中非常常见,例如标准库的begin、cbegin、rbegin等等,我们可以为自己的类设计迭代器方便遍历。