請保持好 - 這是我的第一個問題。 = PC++,實現二叉樹的自定義迭代器(長)
基本上作爲一個暑期項目,我一直在瀏覽wikipedia page上的數據結構列表並試圖實現它們。上個學期我參加了一門C++課程,發現它非常有趣,作爲最後一個項目,我實現了一個Binomial堆 - 這也非常有趣。也許我很討厭,但我喜歡數據結構。
無論如何,足夠的背景故事。該項目進展順利,我從Binary Trees開始。儘管我需要創建遍歷樹的迭代器,但要進一步深入。我已經決定爲每個遍歷方法(常規迭代器和常量迭代器)創建兩種類型的迭代器,但我不知道如何執行此操作。我聽說過從stl的迭代器的東西繼承,甚至使用提升iterator_facade(這似乎是一個很好的選擇)
我甚至沒有試圖寫迭代器代碼,因爲我不知道從哪裏開始,但我在github上有我的當前代碼。你可以看看here。
如果你反對github,我正在粘貼相關的類定義。這些功能的實現不會有任何幫助,但如果您出於某種原因需要它們,請告訴我。此外,節點類還有一個用於迭代目的的父指針。
#ifndef __TREES_HXX
#define __TREES_HXX
#include <cstdlib> // For NULL
#include <algorithm> // for std::max
// Node class definition. These nodes are to be used for any
// tree where the structure is
// node
// /\
// left right
// /\ /\
//
// etc., basically two children.
template <typename T>
class Node
{
public:
T data_;
Node<T>* left_;
Node<T>* right_;
Node<T>* parent_; // Needed for iterators
explicit Node(T const&);
Node(Node<T> const&);
};
template <typename T>
class BinaryTree
{
protected:
typedef Node<T>* node_t;
size_t tree_size;
public:
typedef T value_type;
explicit BinaryTree();
explicit BinaryTree(T const&);
~BinaryTree();
virtual node_t insert(node_t&, T) = 0;
virtual T& lookup(node_t const&, T const&) const = 0;
inline virtual size_t size() const;
inline virtual size_t depth(node_t const&) const;
inline bool empty() const;
inline void clear(node_t);
node_t root;
};
這是我們抽象類的基本二叉樹擴展,基本上它(將)是一個BST。有關爲什麼我需要迭代器的示例,請查看查找函數的定義。它應該將一個迭代器返回到找到該東西的節點。
/* Implementation of our Binary Tree is in
* this file. The node class is in Trees.hxx
* because it's intended to be a general class.
*/
#ifndef __BINARY_TREE_HXX
#define __BINARY_TREE_HXX
#include "Trees.hxx"
template <typename T>
class BiTree : public BinaryTree<T>
{
private:
typedef typename BinaryTree<T>::node_t node_t;
public:
typedef typename BinaryTree<T>::value_type value_type;
BiTree() : BinaryTree<T>()
{
}
BiTree(T const& data) : BinaryTree<T>(data)
{
}
node_t insert(node_t&, T);
T& lookup(node_t const&, T const&) const; // Note: This should return an iterator to the node where the stuff is found
};
我認爲這就是 - 感謝您的時間!如果您需要其他信息,請告訴我。
可能重複的[如何正確實現自定義迭代器和const_iterators?](http://stackoverflow.com/questions/3582608/how-to-correctly-implement-custom-iterators-and-const-iterators) – Nemo 2011-06-16 03:24:27
謝謝爲那個環節。我知道類似的問題已經被問及這一點,(我捨不得發佈問題) - 但它只是好像有意見的就用了什麼方法總體財富(升壓/ STL等,)我想給人們一些特定於我的情況的東西,所以我們可以從那裏走。 – LainIwakura 2011-06-16 03:39:16
(無關你的問題)修正你的頭警衛,他們是非法的 - 從C++ 03標準§17.4.3.1。2/1:「*每個包含雙下劃線('__')的名稱或者以下劃線開頭,後面跟着大寫字母的任何名稱都保留給實施用於任何用途*」 – ildjarn 2011-06-16 03:48:39