二叉搜索树中序迭代器 C++
binary search tree inorder iterator c++
我正在尝试为二叉搜索树实现一个迭代器。我被要求不要在我的迭代器中使用任何 STL。我只需覆盖运算符:++
、operator*
和 !=
。 operator*
出错:"no *operator
matches this operands. Operands types are *iterator<std::string>
"。我正在使用模板库,所以我不确定它为什么不起作用。
这是我的代码:
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
是用于 class 实例化的
我正在尝试为二叉搜索树实现一个迭代器。我被要求不要在我的迭代器中使用任何 STL。我只需覆盖运算符:++
、operator*
和 !=
。 operator*
出错:"no *operator
matches this operands. Operands types are *iterator<std::string>
"。我正在使用模板库,所以我不确定它为什么不起作用。
这是我的代码:
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
是用于 class 实例化的