|
-
Aug 5th, 2002, 07:06 AM
#1
Thread Starter
Hyperactive Member
Looping thru an array, but ReDim in the loop?
Hi Gang,
I'm looping through an array, using UBound as the upper limit of the loop, thus:
VB Code:
For myCount = 0 to UBound(myArray) - 1
' do some stuff
Next
No prob so far.
Then I realised I needed to grown the array under certain circs, inside the loop thus:
VB Code:
For myCount = 0 to UBound(myArray) - 1
' do some stuff
'
Redim Preserve myArray(somevalue)
'
Next
Now the loop doesn't continue to the new end of the array; it still stops at the original end. Even tho' in step mode, if I park the mouse over the For stmt, which shows the UBound has increased, VB seems to have an internal representation of the For..Next's outer limit which it doesn't update.
I've worked around in a way I think is a bit ugly... set the loop's outer limit to be bigger than I expect and then check if I go past the end of the array, thus:
VB Code:
For myCount = 0 to 50 '50 > largest expected value
If myCount > UBound(myArray) Then Exit For
'
' do some stuff
'
Redim Preserve myArray(somevalue)
'
Next
Any one got any better ideas please?
-
Aug 5th, 2002, 07:08 AM
#2
could you maybe have a counter that counts each time you add to the array.. then when you are all done you redim to that value?
-
Aug 5th, 2002, 07:20 AM
#3
Don't use a FOR loop for that, it should only be used when you know the definite bounds to loop BEFORE it starts, try a DO loop instead:
VB Code:
myCount = 0
Do While myCount < UBound(myArray)
' do some stuff
'
Redim Preserve myArray(somevalue)
'
myCount = myCount + 1
Loop
-
Aug 5th, 2002, 07:42 AM
#4
Thread Starter
Hyperactive Member
Thanks Si I'll try that...
Cheers.
-
Aug 5th, 2002, 08:26 AM
#5
PowerPoster
I would actually suggest that if u sorta know that the array may grow u should set the new size before you enter the loop and then reset it back if necessary after the loop completes. Redim preserving inside a loop is extremely slow.
eg Pseudo
Original array is 20 elements
I'm gonna add 5 elements in the loop maybe
Redim Preserve Array (25)
Looping looping
Add a few items
End loop
Hey I only added 3
Redim Preserve (23)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|