添加值时,Fortran数组自动增长 [英] Fortran array automatically growing when adding a value
问题描述
作为一个动机的例子,假设我计算一些递归关系,并且我想存储所有我得到的中间数字。我的停止标准是相邻结果之间的差异,所以我不能预先知道应该为此分配多少内存。
我是
首先,在Fortran 2003中,您可以通过简单的方式添加一个元素
a = [a,item]
由francescalus评论。这可能会经常重新分配数组,并且速度会很慢。
您可以将数组分配给更大的大小,那么元素的数量ñ
。当元素的数量 n
增长到数组 realloc()
。
模块grow_array
隐式无
real,allocatable :: a(:)
integer :: n
包含
子程序add_item(item)
real,allocatable :: tmp(:)
真正的意图(在)::项目
如果(n ==大小(a))然后
!这个语句是F2003,它可以避免,但我不明白为什么在2016
调用move_alloc(a,tmp)
分配(a(n * 2))
a(1:n)= tmp
如果$ b $结束b
n = n + 1
a(n)= item
结束子程序
结束模块
我遗漏了初始分配,这很简单。
它可以放入派生类型中类型绑定的过程,并将其用作数据结构,但这是纯粹的Fortran 2003,而你需要90.因此,我展示了Fortran 95,因为Fortran 90在许多方面存在可分配数组的缺陷,并且已经绝望地过时并且基本上已经死亡。 / p>
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.
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.
这篇关于添加值时,Fortran数组自动增长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!