简体   繁体   中英

binary search tree inorder iterator c++

I am trying to implement an iterator for a binary search tree. I was asked not to use any STL in my iterator. I only have to override the operators: ++ , operator* , and != . I get an error with the operator* : "no *operator matches this operands. Operands types are *iterator<std::string> ". I'm using a template library, so I'm not sure why it's not working.

Here's my code:

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);
        }
    }

};

The code is not well-pasted (see the class Iterator... line). I would recommend removing template <typename T> on bool operator!=(Iterator<T> const & other) const and T &operator*() const methods. Because the T is the one used for the class instantiation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM