2015-11-17 27 views
0

我試圖寫一個由那些地圖節點的二叉搜索樹的迭代器如何寫在C二叉搜索樹的迭代器++使用節點

Node<Key, Value>* node; 

我不得不遍歷集合這些,我真的不知道如何返回一個迭代器。

bool operator!=(const iterator& rhs) const{ ....idk...} 

iterator& operator++(){

第二個是困惑,因爲我不知道怎麼回事迭代&

在此先感謝

+0

'返回*本;' – immibis

回答

0

迭代器就是一個表示特定對象一個容器中的項目(二進制搜索樹)。當你遞增迭代器(用++)時,你移動迭代器來表示容器中的下一個項目。所以你的迭代器必須知道如何遍歷容器中的下一個元素。

您的容器必須能夠提供兩個迭代器。

begin() // returns an iterator to the first element. 
end()  // returns an iterator to the one past the last element. 
      // when an iterator is incremented passed the end of the container 
      // it should compare equal to the iterator returned by this call. 

您需要定義最簡單的迭代器之一(前向迭代器)的操作是:

Node<Key, Value>& operator*()  // Return a reference to the node 
            // That the current iterator represents. 

iterator&   operator++() // Advance the iterator to the next element. 
            // Return a reference to yourself. 

iterator   operator++(int) // Advance the iterator. But return the 
            // original value. 

bool operator!=(iterator const & rhs) // Check if two iterators represent 
             // the same node (or end). return true 
             // if they do not (its not equal). 
+0

我想我會形容爲迭代器的對象, *摘要*和*封裝*容器對象的實現細節,在能夠遍歷容器的實現(例如數組,鏈表,btree等)之前解耦/屏蔽客戶端,而不僅僅是「代表容器中的特定項目「,即使它在迭代過程中指向單個項目。用你的描述,看起來即使是一個原始指針也可以傳遞給一個「迭代器」。 – ray

+0

@ray:原始指針** IS **迭代器的實現(如果容器是C數組)。 –

+0

但是C數組和原始指針不是對象(即類實例),所以我認爲你在這個上下文中超出了適當的術語。迭代器顯然是對[迭代器模式]的引用(https://en.wikipedia.org/wiki/Iterator_pattern) – ray