简体   繁体   English

如何使用节点在C ++中为二进制搜索树编写迭代器

[英]How to write an iterator for a binary search tree in c++ using nodes

I am trying to write an iterator for a binary search tree that consists of nodes that are maps 我正在尝试为包含由节点组成的二叉搜索树编写迭代器

Node<Key, Value>* node; 

I have to iterate over a set of these and I don't really know how to return an iterator. 我必须迭代其中的一组,但我真的不知道如何返回迭代器。

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

iterator& operator++(){

The second one is confusing because I'm not sure how to return a iterator& 第二个令人困惑,因为我不确定如何返回迭代器&

Thanks in advance 提前致谢

An iterator is just an object that represents a particular item in a container (your binary search tree). 迭代器只是一个对象,它表示容器(您的二进制搜索树)中的特定项目。 When you increment the iterator (with ++) you move the iterator to represent the next item in the container. 当增加迭代器(使用++)时,将移动迭代器以表示容器中的下一项。 So your iterator must know how to traverse to the next element in the container. 因此,迭代器必须知道如何遍历容器中的下一个元素。

Your container must be able to provide two iterators. 您的容器必须能够提供两个迭代器。

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.

The operations you need to define for one of the simplest iterator (Forward Iterator) are: 您需要为最简单的迭代器之一(Forward Iterator)定义的操作是:

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).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM