我有一个用C++实现的红黑树。它支持STL映射的功能,树节点包含键和相应的映射值。我想为此编写一个迭代器类,但是我不知道该如何着手。我应该将其定义为树类的内部类吗?请问有什么写法指南和资源可以提供吗?
感谢您!
感谢您!
当然,阅读这篇关于编写STL迭代器的好文章可能会为您提供所需的概述:
http://www.drdobbs.com/184401417
通常情况下,内部类是很好的选择,因为迭代器需要访问您特定实现的树节点:
struct container { ...
public:
struct iterator {
// these typedefs are needed if you want to be STL compatible
typedef std::forward_iterator_tag iterator_category;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
// the element points to your implementation node
iterator( element* init = 0 ) : current(init) {}
T& operator*() { return current->data; } // dereference
const T& operator*() const { return current->data; }
iterator& operator++() { // prefix
if ( current ) current = current->next;
return *this;
}
iterator operator++(int) { // postfix
iterator temp = *this;
++*this;
return temp;
}
bool operator==(const iterator& x) const { return current == x.current; }
bool operator!=(const iterator& x) const { return current != x.current; }
private:
// the element points to your implementation node
element* current;
}
...
这里的好处是,虽然迭代器是公共的,但元素仍然可以保持私有状态 :). 而且,上面的代码也符合STL标准!
iterator( element* init = 0 ) { current = init;}
相同。 - Kornel Kisielewicznamespace detail {
template <class Value> class base_iterator;
}
template <class Value>
class container
{
public:
typedef detail::base_iterator<Value> iterator;
typedef detail::base_iterator<Value const> const_iterator;
typedef boost::reverse_iterator<iterator> reverse_iterator;
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
};
我不知道你是否有同感,但是当我只需要完成四分之一的工作并使用编译器/库来填充其余部分时,我会感觉很好 :)
your_map::iterator
别名为在其他地方定义的某种类型。嵌套类通常是最干净/最简单的路线。