Fortran array automatically growing when adding a

2019-07-12 18:45发布

Is there any existing way to emulate growing array in Fortran? Like vector in C++. I was very surprised when I haven't found anything on this subject on the Internet.

As a motivation example, suppose I compute some recurrence relation and I want to store all the intermediate numbers I get. My stopping criterion is the difference between adjacent results so I cannot know beforehand how much memory I should allocate for this.

1条回答
The star\"
2楼-- · 2019-07-12 19:16

I am sure it has been shown somewhere on this site before, but I cannot find it.

First, in Fortran 2003, you can add one element by simple

a = [a, item]

as commented by francescalus. This is likely to reallocate the array very often and will be slow.

You can keep your array to be allocated to somewhat larger size then your number of elements n. When your number of elements n grows above the size of the array size(a) you can allocate a new array larger by some factor (here 2x) and copy the old elements there. There is no realloc() in Fortran, unfortunately.

module growing_array
  implicit none

  real, allocatable :: a(:)

  integer :: n

contains

  subroutine add_item(item)
    real, allocatable :: tmp(:)
    real, intent(in) :: item

    if (n == size(a)) then
      !this statement is F2003, it can be avoided, but I don't see why in 2016
      call move_alloc(a, tmp)

      allocate(a(n*2))
      a(1:n) = tmp
    end if

    n = n + 1

    a(n) = item
  end subroutine
end module

I left out the initial allocation, it is simple enough.

It all can be put into a derived type with type-bound procedures, and use it as a data structure, but that is pure Fortran 2003 and you wanted 90. So I show Fortran 95, because Fortran 90 is flawed in many ways for allocatable arrays and is desperately obsolete and essentially dead.

查看更多
登录 后发表回答