Using a List Iterator Class
If you write a separate iterator class that walks through the items in the list, you’ll be able to create multiple iterator objects. Each one will be able to walk through the list separately. Who would want a road with only one car permanently
attached? It’s much better to make the road and the car separate objects and
allow multiple cars at different places on the same road. If you’re not convinced by this analogy, hold your piece. There are other reasons for separate iterators.
Here’s an example of how to use an iterator:
Dim walker As New CListWalker
walker.Attach list
Do While walker.More
s = s & Space$(4) & walker & sCrLf
Loop
First you have to tell the iterator object which list to iterate by passing a list object to the Attach method. Then you loop through the items in the list. The Item property is the default member, so you can omit the method name. The CLink, CList, and CListWalker classes all have default Item properties. Don’t confuse them.
Since CListWalker is a separate class, two objects can iterate separately without interfering with each other. For example, here’s a nested iterator. The outside iterator walks partway, then the inside iterator walks the entire list, and finally the outside iterator regains control and continues where it left off:
Dim walker2 As New CListWalker
s = s & “Nesting iterate:” & sCrLf
walker.Attach list
Do While walker.More
s = s & Space$(4) & walker & sCrLf
If walker = “Pig” Then
walker2.Attach list
s = s & Space$(4) & “Nested iterate:” & sCrLf
Do While walker2.More
s = s & Space$(8) & walker2 & sCrLf
Loop
End If
Loop
Stop! You probably think I’m missing the obvious. You don’t want to iterate with Do Loop. You want to iterate with For Each. It should be simple:
s = s & “Iterate with For Each:” & sCrLf
Dim v As Variant
For Each v In list
s = s & Space$(4) & “V: “ & v & sCrLf
Next
That does, in fact, work, but I’m not going to tell you why until the end of the chapter. For now, all I can say is that classes that work with For Each work because they have an iterator class just as CList has a CListWalker.