我試圖寫一個C++程序提供節點,以這種循環:創建一個C++序迭代器提供樹節點的循環
bin_tree<int> *my_tree = ...
for (bin_tree<int>::iterator n = my_tree->begin();
n != my_tree->end(); ++n)
{
cout << *n << "\n";
}
類我是用Java編寫的,我會喜歡把它翻譯成C++,但是我很難這樣做。這是類:
class BinTree<T> implements Iterable<T> {
BinTree<T> left;
BinTree<T> right;
T val;
// other methods: insert, delete, lookup, ...
public Iterator<T> iterator()
{
return new TreeIterator(this);
}
private class TreeIterator implements Iterator<T>
{
private Stack<BinTree<T>> s = new Stack<BinTree<T>>();
TreeIterator(BinTree<T> n)
{
if (n.val != null) s.push(n);
}
public boolean hasNext()
{
return !s.empty();
}
public T next()
{
if (!hasNext()) throw new NoSuchElementException();
BinTree<T> n = s.pop();
if (n.right != null) s.push(n.right);
if (n.left != null) s.push(n.left);
return n.val;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
如何在C++中正確編寫這個程序的任何幫助,將不勝感激,我不知道如何正確地貫徹序迭代器。