我希望有一个真正的Fortran程序员,但是在没有更好建议的情况下,我只会指定形状而不是大小
x(:),使用一个临时数组
temp(size(x)),并输出y
allocatable。然后,在第一遍之后,
allocate(y(j))从临时数组中复制值。但是我不能强调自己不是Fortran程序员,所以我不能说该语言是否具有可增长的数组或是否存在用于后者的库。
program test implicit none integer:: x(10) = (/1,0,2,0,3,0,4,0,5,0/) print "(10I2.1)", select(x)contains function select(x) result(y) implicit none integer, intent(in):: x(:) integer:: i, j, temp(size(x)) integer, allocatable:: y(:) j = 0 do i = 1, size(x) if (x(i) /= 0) then j = j + 1 temp(j) = x(i) endif enddo allocate(y(j)) y = temp(:j) end function selectend program test
编辑:
基于MSB的答案,这里是一种生长功能的修订版 温度
y与超额分配。
事实证明,我没有必要以最终大小显式分配新数组。相反,它可以通过分配自动完成。
function select(x) result(y) implicit none integer, intent(in):: x(:) integer:: i, j, dsize integer, allocatable:: temp(:), y(:) dsize = 0; allocate(y(0)) j = 0 do i = 1, size(x) if (x(i) /= 0) then j = j + 1 if (j >= dsize) then !grow y using temp dsize = j + j / 8 + 8 allocate(temp(dsize)) temp(:size(y)) = y call move_alloc(temp, y) !temp gets deallocated endif y(j) = x(i) endif enddo y = y(:j) end function select



