Visual Basic中未知长度的数组 [英] Arrays of unknown length in Visual Basic
问题描述
我有一段用Visual Basic编写的代码:
I have a piece of code written in Visual Basic:
Dim n As Double, i As Integer
n = 4
Dim Ramp_length(1 To 4) As Double
For i = 1 To n
Ramp_length(i) = Cells(13 + i, 5)
'Cells(65 + i, 7) = Ramp_length(i)'
Next i
有没有办法我可以在不声明长度为固定的情况下重现结果吗?我最终希望代码读取长度未知的数据列,并将其存储在相等或较小长度的数组中,以便可以对其进行更改。这只是一部分代码...如果有人可以帮助我,那就太好了! :D
Is there a way I can reproduce the result without declaring the array with a "fixed" length? I eventually want the code to read off a column of data with unknown length and store it in an array of equal or smaller length so it can be altered. This is just a piece of the code...if someone could help me out that would be great! :D
谢谢
推荐答案
您可以使用ReDim Preserve调整大小数组。如果您只需要查看时间并且不循环使用它就可以了。但是ReDim Preserve速度很慢,因为它会创建一个全新的数组并将旧值复制到其中。
如果您需要用未知数量的数据集填充数组,请使用列表。我举了一个小例子:
You can use ReDim Preserve to resize an array. If you only need it a view times and don't use it in a loop, it's ok. But ReDim Preserve is very slow, because it creates a completely new array and copies the old values into it. If you need to fill an array up with an unknown amount of data sets, use a list. I made a small example:
Dim num_iterations as Integer
' redim solution
Dim dyn_array As Integer()
For i = 0 To num_iterations - 1
ReDim Preserve dyn_array(i)
dyn_array(i) = i
Next
' list solution
Dim list_for_array As New List(Of Integer)
For i = 0 To num_iterations - 1
list_for_array.Add(i)
Next
Dim list_array As Integer() = list_for_array.ToArray
通过10000次迭代,ReDim-solution的运行时间为32ms,列表解决方案立即准备就绪(0毫秒)。 100000次迭代使用ReDim产生5487毫秒,使用列表产生1毫秒。
With 10000 iterations the ReDim-solution has a runtime of 32ms, the list solution is instantly ready (0 ms). 100000 iterations result in 5487ms using ReDim and 1ms using a list.
这篇关于Visual Basic中未知长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!