不同长度的多维数组
问题描述:
我正在尝试在第二维中创建一个具有不同长度的数组,例如:
I am trying to make an array with different lengths in a second dimension e.g.:
A = 1 3 5 6 9
2 3 2
2 5 8 9
这可能吗?我花了很多时间寻找,但无法找到任何一种方法.
Is this possible? I've spent a fair amount of time looking but cannot find out either way.
答
是和否.首先没有:
Fortran 中的正确数组,例如如下声明的数组:
Proper arrays in Fortran, such as those declared like this:
integer, dimension(3,3,4) :: an_array
或者像这样
integer, dimension(:,:,:,:), allocatable :: an_array
是常规的;每个维度只有一个范围.
are regular; for each dimension there is only one extent.
但是,如果你想为一个参差不齐的数组定义你自己的类型,你可以,而且相对容易:
But, if you want to define your own type for a ragged array you can, and it's relatively easy:
type :: vector
integer, dimension(:), allocatable :: elements
end type vector
type :: ragged_array
type(vector), dimension(:), allocatable :: vectors
end type ragged_array
通过这种方法,您可以将每个 vectors
的 elements
分配到不同的大小.例如:
With this sort of approach you can allocate the elements
of each of the vectors
to a different size. For example:
type(ragged_array) :: ragarr
...
allocate(ragarr%vectors(5))
...
allocate(ragarr%vectors(1)%elements(3))
allocate(ragarr%vectors(2)%elements(4))
allocate(ragarr%vectors(3)%elements(6))