C++链表迭代器类

C++ Linked List Iterator Class

本文关键字:迭代器 链表 C++      更新时间:2023-10-16

我为一个项目创建了一个单独的链表,现在需要创建一个自定义的Iterator类。我的链表中有一个嵌套类,它定义了我的迭代器。我已经编写了大部分课程,但对如何实现一些函数感到困惑。我的问题如下:

-请看我的end()函数。我将其设置为Iterator类的默认构造函数,因此迭代器中的currentNode变量默认为NULL。这是否正确实施?

-我应该如何重载Iterator类中的->运算符?

class SSLL_Iter : public std::iterator<std::forward_iterator_tag, T>
    {
    public:
        typedef T value_type;
        typedef std::ptrdiff_t difference_type;
        typedef T& reference;
        typedef T* pointer;
        typedef std::forward_iterator_tag iterator_category;
        typedef SSLL_Iter self_type;
        typedef SSLL_Iter& self_reference;
    private:
        Node* currentNode;
    public:
        explicit SSLL_Iter( Node* start = NULL) : currentNode( start ) {}   //****************complete
        SSLL_Iter( const SSLL_Iter& src ) : currentNode( src.currentNode ) {}      //****************complete
        reference operator*() const {   //****************complete
            T& temp = (currentNode->data);
            return temp;
        }
        pointer operator->() const {}  //*******??????????????????
        self_reference operator=( const SSLL_Iter& src ) {     //****************complete
            this->here = src.here;
            return *this;
        }
        self_reference operator++() { // preincrement         //****************complete
            currentNode = currentNode->next;
            return *this;
        }
        self_type operator++(int) {  // postincrement         //****************complete
            self_type temp = (*this);
            ++(*this);
            return temp;
        }
        bool operator==(const SSLL_Iter& rhs) const {        //****************complete
            return (this->currentNode == rhs.currentNode);
        }
        bool operator!=(const SSLL_Iter& rhs) const {        //****************complete
            return (this->currentNode != rhs.currentNode);
        }
    }; // end SSLL_Iter
    typedef std::size_t size_t;
    typedef T value_type;
    typedef SSLL_Iter iterator;
    //typedef Const_SSL_Iter const_iterator;
    SSLL() {}
    SSLL(const SSLL& src ) {
        for(int i = 0; i < src.size(); ++i) {    // populate this SSLL with copies of the other SSLL's    contents
            this->push_back(src.item_at(i));
        }
    }
    ~SSLL() {
        if(!is_empty()) {
            clear();
        }
    }
    iterator begin() { return SSLL_Iter( head ); }
    iterator end() { return SSLL_Iter(); }

return &*(*this);是一个不错的operator->

您的SSLL类可能没有有效的at,所以不要在复制构造函数中使用它。相反,创建一个SSLL template<class Iterator> void append(Iterator s, Iterator f),并根据它实现SSLL(const SSLL& src)

如果您支持C++11,请考虑将Nodenext节点替换为std::unique_ptr<Node>。对指向SSLL根目录中第一个Node的指针执行相同操作。现在,内存管理几乎是自动处理的。更改后,您可能需要在迭代器中使用.get()。这也消除了析构函数的主体,使移动构造函数=default正确(除非你在计算节点)等。