Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

vector - Fortran array automatically growing when adding a value

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...