问题的简化描述:
确实有maxSize人在商店购物.他们每个都有一个购物清单,包含物品的价格(作为整数).使用Fortran数组,我如何表示所有购物清单.购物清单可以包含任意数量的项目(1,10,1000000000).
(注意:实际问题要复杂得多.甚至不是购物.)
懒惰的方法是:
integer :: array(maxSize, A_REALLY_BIG_NUMBER)
Run Code Online (Sandbox Code Playgroud)
然而,这是非常浪费的,我基本上希望第二个维度是可变的,然后单独为每个人分配它.
注定要失败的显而易见的尝试:
integer, allocatable :: array(:,:)
allocate(array(maxSize, :)) ! Compiler error
Run Code Online (Sandbox Code Playgroud)
Fortran似乎要求数组在每个维度上都有固定的大小.
这很奇怪,因为大多数语言将多维数组视为"数组数组",因此您可以单独设置"数组数组"中每个数组的大小.
下面是一些做的工作:
type array1D
integer, allocatable :: elements(:) ! The compiler is fine with this!
endtype array1D
type(array1D) :: array2D(10)
integer :: i
do i=1, size(array2D)
allocate(array2D(i)%elements(sizeAt(i))
enddo
Run Code Online (Sandbox Code Playgroud)
如果这是唯一的解决方案,我想我会用它.但我有点希望有一种方法可以使用内在函数来做到这一点.必须为这么简单的东西定义自定义类型有点烦人.
在C中,由于数组基本上是具有花哨语法的指针,因此您可以使用指针数组执行此操作:
int sizeAt(int x); //Function that gets the size in the 2nd dimension
int * array[maxSize];
for (int x = 0; x < maxSize; …
Run Code Online (Sandbox Code Playgroud)