Reputation: 2902
I am trying to create city distances array CityDistances(CityId1, CityId2) = Distance
As I don't know how many citys there would be, I need an unlimited array. I tried creating it via Dim CityDistances(,) As Double
, but when I try to use it, it throws an exception. How do I achieve that?
Upvotes: 0
Views: 6598
Reputation: 216293
Instead of an array, a possibly better alternative (and a little more OOP) is through the use of a List(Of Type)
.
Dim d As List(Of DIstances) = New List(Of Distances)()
d.Add(New Distances() With {.CityID1=1, .CityID2=2, .Distance=12.4})
d.Add(New Distances() With {.CityID1=1, .CityID2=3, .Distance=15.1})
d.Add(New Distances() With {.CityID1=1, .CityID2=4, .Distance=2.4})
d.Add(New Distances() With {.CityID1=1, .CityID2=5, .Distance=130.1})
Public Class Distances
Public CityID1 as Integer
Public CityID2 as Integer
Public Distance as Double
End Class
This has the advantage to let your list grow without specifying any initial limits.
Upvotes: 3
Reputation: 26424
First of all, by doing this:
Dim CityDistances(,) As Double
You declare a pointer to a two dimensional array, without performing any memory allocation for its elements. It is expected that some method will return this array, and you will use it via this pointer. If you try to use it AS IS, without assigning anything to it, you will get index-out-of-bounds
exception, which is normal.
Second, there is no such thing as unlimited arrays. You need to be using list of lists, dictionary of dictionaries, a DataTable
or similar, if you want automatic memory management. If you want to stick with arrays, for performance/convenience reasons, you can ReDim
it when required (increase dimensions), and preserve contents, like this:
Dim CityDistances(,) As Double
ReDim Preserve CityDistances(10,10)
'.... code goes here ....
ReDim Preserve CityDistances(100,100)
Make sure you know when to ReDim, because every time you do it, .NET will create another array and copy all elements there. As the size of your array grows, it may become a performance factor.
Third, based on the nature of your question, you may want to look into custom implementations of the Matrix
class. Here are some links I found through Google, hope you find them useful. Those are C#, but there are free online converters to VB.NET on the internet.
Lightweight fast matrix class in C# (Strassen algorithm, LU decomposition) (free)
Efficient Matrix Programming in C# (code-project, so free as well)
High performance matrix algebra for .NET programming! (paid, 99$ and up)
Upvotes: 1