Fortran 数组在添加值时自动增长 [英] Fortran array automatically growing when adding a value
问题描述
是否有任何现有方法可以在 Fortran 中模拟不断增长的数组?就像 C++ 中的向量.当我在 Internet 上没有找到有关此主题的任何内容时,我感到非常惊讶.
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.
推荐答案
我确信它以前曾在本网站的某个地方展示过,但我找不到.
I am sure it has been shown somewhere on this site before, but I cannot find it.
首先,在 Fortran 2003 中,您可以通过简单的方式添加一个元素
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.
您可以将数组分配到比元素数n
更大的大小.当您的元素数量 n
增长到超过数组 size(a)
的大小时,您可以分配一个更大的新数组(此处为 2x)并复制旧元素那里.不幸的是,Fortran 中没有 realloc()
.
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.
这一切都可以放在带有类型绑定过程的派生类型中,并将其用作数据结构,但那是纯 Fortran 2003 而你想要 90.所以我展示 Fortran 95,因为 Fortran 90 在许多方面存在缺陷可分配数组的方法,已经过时了,基本上已经死了.
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.
这篇关于Fortran 数组在添加值时自动增长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!