Using Vectors


Before Collections, Visual Basic programmers used to get around the array size problem by resizing arrays in chunks. My CVector class uses the chunk technique but hides the ugly details.


As usual, I’ll show you what you can do with a CVector before I show you how it works. Here’s a typical initialization loop:

Dim vector As New CVector, i As Long, s As String
s = “Insert numbers in vector: “ & sCrLf
For i = 1 To 15
vector(i) = i * i
s = s & Space$(4) & i * i & “: vector(“ & i & “)” & sCrLf
Next

Vectors can grow to whatever size you want. Just keep adding more elements, and the vector automatically adjusts.


Notice that the vectors are one-based. That’s a design choice. I could have started them at 0 or -1 or 5. In an early implementation, I started them at 0 but often used them as if they started at 1. Since vectors always waste space, I felt wasting that extra 0 element wasn’t a big deal. But with use, I discovered that ignoring that extra element wasn’t such a good idea. If you like negative vectors, go ahead, but you’ll end up with a different class with different implementation problems.


Don’t worry about inserting elements far beyond the end of the array. That works. You can even initialize from the top down:

For i = 100 To 1 Step -1
vv(i) = i * i
Next

Normally, you’ll want to read only the elements that have been initialized:

s = s & “Read numbers from vector: “ & sCrLf
For i = 1 To vector.Last
s = s & Space$(4) & “vector(“ & i & “) = “ & vector(i) & sCrLf
Next

The vector keeps track of the last element to be initialized and reports it through the Last property.


CVector addresses the problem of growing arrays, but what about shrinking arrays? Well, it is possible to shrink the vector by setting the Last property:

s = s & “Shrink vector to 5 and read numbers: “ & sCrLf
vector.Last = 5
For i = 1 To vector.Last
s = s & Space$(4) & “vector(“ & i & “) = “ & vector(i) & sCrLf
Next

s = s & “Read numbers with For Each: “ & sCrLf
Dim v As Variant
For Each v In vector
s = s & Space$(4) & “v = “ & v & sCrLf
Next

If you shrink the vector, all the elements beyond the new Last get thrown into the bit bucket. Expanding the vector to the original size won’t bring them back, and there’s no way to delete entries in the middle of the vector. As with arrays, entries stay exactly where you put them unless you move them.


If this looks too good to be true, well, there is a cost—and it’s one that experienced programmers know well. You spend data space to get better performance.