fortran子程序:任意类型的数组 [英] fortran subroutine: array of arbitrary type
问题描述
我试图编写一个子程序来颠倒数组的行。以下工作,但显式声明其输入arr的类型。因此,我需要一个单独的子程序为real类型的数组做同样的事情。当然有一种方法可以让它接受任意类型的数组 - 有人可以帮我理解语法吗?
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' inout):: arr
integer,dimension(:, :),allocatable :: tmp
整数i,j,nrow,ncol,ierr
nrow = size(arr, 1)
ncol = size(arr,2)
allocate(tmp(nrow,ncol),STAT = ierr)
tmp(:,, :) = arr(nrow:1:-1,:)
arr = tmp
deallocate(tmp)
END SUBROUTINE flipud
Fortran没有相当于C ++模板。您可以使用模块过程创建一个接口,如下所示。这两个子例程通用的代码可以放在使用INCLUDE语句合并的文件中。
module foo
接口fliupud
模块过程flipud_i,flipud_r
结束接口flipud
包含
子例程flipud_i(arr)
整数,维(:, :): ,intent(inout):: arr
! body
结束子程序flipud_i
!
子程序flipud_r(arr)
实数,维(:, :),意图(inout):: arr
! body
结束子程序flipud_r
结束模块foo
I'm trying to write a subroutine to reverse the rows of an array. The following works, but explicitly declares the type of its input arr. Thus I'd need a separate subroutine to do the same thing for an array of type real. Surely there's a way to make it accept an array of arbitrary type - could someone help me with the syntax? Thanks!
SUBROUTINE flipud(arr)
integer, dimension(:,:), intent(inout) :: arr
integer, dimension(:,:), allocatable :: tmp
integer i, j, nrow, ncol, ierr
nrow = size(arr, 1)
ncol = size(arr, 2)
allocate(tmp(nrow, ncol), STAT=ierr)
tmp(:,:) = arr(nrow:1:-1, :)
arr = tmp
deallocate(tmp)
END SUBROUTINE flipud
Fortran does not have the equivalent of C++ templates. You can create an interface with module procedures, as sketched below. The code that is common to both subroutines could be placed in a file that is incorporated using the INCLUDE statement.
module foo
interface fliupud
module procedure flipud_i,flipud_r
end interface flipud
contains
subroutine flipud_i(arr)
integer, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_i
!
subroutine flipud_r(arr)
real, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_r
end module foo
这篇关于fortran子程序:任意类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!