2014-12-13 87 views
2

我的C++代碼有點問題。我在頭變量列表,列表中的最後和實際節點(下圖)鏈表,我需要讓我自己的(學校工作)迭代器..C++自己的迭代器

list http://www.attanon.eu/list.png

我有。

我的類迭代器是本

class iterator 
{ 
    Node* _node; 
public: 
    iterator(Node* node) : _node(node){} 
    ~iterator(){ _node = nullptr; } 

    iterator& operator=(const iterator& other) 
    { 
     _node = other._node; 
     return *this; 
    } 
    bool operator==(const iterator& other) 
    { 
     if (_node == nullptr || other._node == nullptr) 
     { 
      return false; 
     } 
     else 
     { 
      return _node->_data == other._node->_data; 
     } 
    } 
    bool operator!=(const iterator& other) 
    { 
     if (_node == nullptr || other._node == nullptr) 
     { 
      return false; 
     } 
     else 
     { 
      return _node->_data != other._node->_data; 
     } 
    } 

    iterator& operator++() // prefix 
    { 
     if (_node != nullptr) 
     { 
      _node = _node->_next; 
     } 
     return *this; 
    } 
    iterator operator++(int) // postfix 
    { 
     iterator temp(*this); 
     ++(*this); 
     return temp; 
    } 
    T& operator*() // dereference 
    { 
     return _node->_data; 
    } 
    T* operator->() // šipková notace 
    { 
     return &*(List<T>::iterator)*this; 
    } 
}; 

,我需要做的方法開始和結束的迭代throught名單。

我嘗試這種方式,但與此實現我沒有得到列表的最後一個節點。

iterator begin() 
{ 
    return iterator(_head); 
} 

iterator end() 
{ 
    return iterator(_last); 
} 

任何人都可以幫助我如何使這兩種方法?

P.S.對不起,我的英語不好,我知道。

感謝您的幫助

編輯:

我的節點類是該

class Node 
{ 
public: 
    T _data; 
    Node* _next; 
}; 

我用它進行循環測試..

for (List<int>::iterator it = list->begin(); it != list->end(); it++) 
{ 
    std::cout << *it << std::endl; 
} 

回答

6

結束迭代器應該是到「過去 - 結束」元素,而不是實際的最後一個元素。所以,你要真有:

iterator end() 
{ 
    return iterator(nullptr); 
} 

,然後實現operator==爲:

bool operator==(const iterator& other) { return _node == other._node; } 
bool operator!=(const iterator& other) { !((*this) == other); } 

,使其接受nullptr

+0

我找到了這種方式,但有了這個我需要重做我的迭代器操作符,因爲它沒有顯示任何想法。 – JAttanonRadar 2014-12-13 18:40:25

+0

@JAttanonRadar你的意思是「它沒有顯示任何東西」是什麼意思? – Shoe 2014-12-13 18:42:36

+0

如果我使用測試功能,它不是列表中的數據.. – JAttanonRadar 2014-12-13 18:44:14