Using a Stack


Before we get into implementation details, here’s how you use the interface and the classes that implement it:

txtOut.Text = s
txtOut.Refresh
Dim beasts As IStack
Select Case GetOption(optStack)
Case 0
Set beasts = New CStackLst
Case 1
Set beasts = New CStackVec
Case 2
Set beasts = New CStackCol
End Select
s = s & Space$(4) & “Push Lion” & sCrLf
beasts.Push “Lion”
s = s & Space$(4) & “Push Tiger” & sCrLf
beasts.Push “Tiger”
s = s & Space$(4) & “Push Bear” & sCrLf
beasts.Push “Bear”
s = s & Space$(4) & “Push Shrew” & sCrLf
beasts.Push “Shrew”
s = s & Space$(4) & “Push Weasel” & sCrLf
beasts.Push “Weasel”
s = s & Space$(4) & “Push Yetti” & sCrLf
beasts.Push “Yetti”

s = s & “Pop animals off stack: “ & sCrLf
Do While beasts.Count
s = s & Space$(4) & “Pop “ & beasts.Pop & sCrLf
Loop

In the example, an array of option buttons determines which class will be ­instantiated with the IStack object variable. (The sidebar on the following page demonstrates the GetOption function.) The output looks like this:

Push animals onto stack:
Push Lion
Push Tiger
Push Bear
Push Shrew
Push Weasel
Push Yetti
Pop animals off stack:
Pop Yetti
Pop Weasel
Pop Shrew
Pop Bear
Pop Tiger
Pop Lion

In addition, the sample starts timing, pushes the number of integers specified by the Count text box onto a stack, pops them off, and then stops the timing. You can check the source in TCOLLECT.FRM. I’ll tell you the timing results later.

A Control Array Is Not an Array
One of the least understood data structures in Visual Basic is the control array. You won’t find it in the object browser and the documentation on it is…well, it exists, but not necessarily where you expect to find it.


The most important feature of a control array is that it isn’t an array. It’s more like a collection, complete with properties and an iterator. Here’s a summary of what I’ve been able to figure out.


First, a control array has LBound and UBound properties. Don’t confuse these with the LBound and UBound functions, which take a real array (but not a control array) as a parameter. A control array also has a Count property, but the count isn’t necessarily the same as the number of places in the array (UBound - LBound + 1) because a control array can have unused entries. The best way to handle a control array is to ignore the properties and iterate with For Each. That way you skip any empty entries.


Here’s an example that solves the annoying problem of trying to figure out which option button is selected in a control array of option buttons:

‘ Find the True option from a control array of OptionButtons
Function GetOption(opts As Object) As Integer
On Error GoTo GetOptionFail
Dim opt As OptionButton
For Each opt In opts
If opt.Value Then
GetOption = opt.Index
Exit Function
End If
Next
On Error GoTo 0
ErrRaise eeNoTrueOption
Exit Function
GetOptionFail:
ErrRaise eeNotOptionArray
End Function

The error handling technique used here is explained in Chapter 5.