In contrast, a two-dimensional array is always rectangular.
The file 'jaggedarray.bi' below to include allows to macro-generate a Jagged Array UDT structure depending on the user Datatype:
- - A constructor 'jaggedArrayDatatype(() As Integer)' allocates memory/datatype and sizes the instance ('array' for example), from a 1D array containing the number of columns for each row.
- The syntax for accessing an element '(r, c)' of the jagged array is 'array[r][c]' ('array' being the constructed instance).
- A destructor automatically frees the memory when the constructed instance is going out of scope.
Code: Select all
#macro jaggedArray(typename)
#ifndef jaggedArray##typename
Type jaggedArray_##typename
Public:
Declare Constructor (Byval size As Integer)
Declare Operator [] (Byval index As Integer) Byref As typename
Private:
Dim As typename array(Any)
End Type
Constructor jaggedArray_##typename (Byval size As Integer)
Redim This.array(size - 1)
End Constructor
Operator jaggedArray_##typename.[] (Byval index As Integer) Byref As typename
Return This.array(index)
End Operator
Type jaggedArray##typename
Public:
Declare Constructor (size() As Integer)
Declare Destructor ()
Declare Operator [] (Byval index As Integer) Byref As jaggedArray_##typename
Private:
Dim As jaggedArray_##typename Ptr array(Any)
End Type
Constructor jaggedArray##typename (size() As Integer)
Redim This.array(Ubound(size) - Lbound(size))
For I As Integer = Lbound(size) To Ubound(size)
This.array(I - Lbound(size)) = New jaggedArray_##typename(size(I))
Next I
End Constructor
Destructor jaggedArray##typename ()
For I As Integer = Lbound(This.array) To Ubound(This.array)
Delete This.array(I)
Next I
End Destructor
Operator jaggedArray##typename.[] (Byval index As Integer) Byref As jaggedArray_##typename
Return *This.array(index)
End Operator
#endif
#endmacro
- - Construct a jagged array of String of 3 rows:
- - first row has 5 columns,
- second row has 3 columns,
- third row has 4 columns.
- Check the values of all elements. - - first row has 5 columns,
Code: Select all
#include "jaggedarray.bi"
jaggedArray(String)
Dim As Integer size(...) = {5, 3, 4}
Dim As jaggedArrayString array = size()
For I As Integer = Lbound(size) To Ubound(size)
For J As Integer = 0 To size(I) - 1
array[I - Lbound(size)][J] = Str(I - Lbound(size)) & Str(J)
Next J
Next I
For I As Integer = Lbound(size) To Ubound(size)
For J As Integer = 0 To size(I) - 1
Print array[I - Lbound(size)][J],
Next J
Print
Next I
Sleep
- Output:
Code: Select all
00 01 02 03 04 10 11 12 20 21 22 23