Walking the CThings collection


The wizard does an even better job on the CThingWalker class. You can simply go through and eliminate the search-and-replace comment markers, accepting all the wizard’s suggestions. The wizard’s suggestions are optimized for array-based collections; often you can use them with little or no change. Without showing all the code, I’ll just accept the suggestion to name the state variable iCur and initialize it to 0.


Wait a minute. If the array had the values 1 through 10, why would I initialize iCur to 0? Let’s take a look at IVariantWalker_More to see why:

‘ Implement IVariantWalker methods
Private Function IVariantWalker_More(v As Variant) As Boolean
‘ Move to next element
iCur = iCur + 1
‘ If more data, return True and update data
If iCur <= connect.Count Then
IVariantWalker_More = True
v = connect.Things(iCur)
End If
End Function

The More method advances to the next element and returns that element. You need to start iCur at 0 so that when you advance the first time through, you end up pointing at the first element. This works with an array-based collection, but sometimes you’ll need to check a flag or other condition to identify the first element and handle it differently. In this array-based collection, you can use the Count property to identify the last element, but other types of collections will find the end with other techniques.


The Reset and Skip methods reinitialize the state variable and advance it the given number of places, respectively:

Private Sub IVariantWalker_Reset()
‘ Move to first element
iCur = 0
End Sub

Private Sub IVariantWalker_Skip(c As Long)
‘ Skip a given number of elements
iCur = iCur + c
End Sub

The CThings collection is too good to be true. Let’s revisit some familiar ­collections—CList and CVector—to see more realistic implementations.