Iterator Design Pattern

Β·

1 min read

  • An iterator is an object that facilitates the traversal of a data structure

    • It keeps a ref to the current element

    • Knows how to move to a different element

    • Ex. Above are inbuilt C++ forward and reverse iterators. You can also get constant iterators using crbegin()

    • In C++ the range-based for-loop has no reverse iterator

Building an iterator for a Binary Tree

  • Let us define a BinaryTree Node class of generalised key value

  • Similarly, let's define a class BinaryTree which maintains our Binary Tree

  • Now we we will build a Pre-order iterator for this tree (Node->Left->Right)

  • We can also set this as the default iterator for our BinaryTree class

  • Now to finally create a tree, we can do something like the below

Β