二叉搜索树inorder迭代器C++
问题描述:
我正在尝试为二叉搜索树实现迭代器。我被要求不要在我的迭代器中使用任何STL。我只需要覆盖运营商:++
,operator*
和!=
。我在operator*
错误:“没有*operator
匹配这个操作数,操作数类型是*iterator<std::string>
”。我正在使用模板库,所以我不确定它为什么不起作用。二叉搜索树inorder迭代器C++
这里是我的代码:
template <typename T>
class Iterator : public std::iterator<std::forward_iterator_tag, {
public:
Iterator(TreeNode<T>* root)
{
this->current = root;
}
template <typename T>
bool operator!=(Iterator<T> const & other) const
{
return this->current != other.current;
}
template <typename T>
T &operator*() const {
return current->element;
}
Iterator operator++()
{
current = current->nextInorder();
return *this;
}
Iterator operator++(int dummy)
{
TreeNode<T> temp = current;
current = current->nextInorder();
return *temp;
}
private:
TreeNode<T>* current;
void nextInorder()
{
if (current->element == NULL)return;
else {
nextInorder(current->left);
nextInorder(current->element);
nextInorder(current->right);
}
}
};
答
的代码是没有得到很好的粘贴(见class Iterator...
线)。 我会建议在bool operator!=(Iterator<T> const & other) const
和T &operator*() const
方法上删除template <typename T>
。因为T
是用于类实例化的。