目前在我的代码中我有一个二维数组
integer, allocatable :: elements(:,:)
并定义一些常量
integer, parameter :: TYP = 1
integer, parameter :: WIDTH = 2
integer, parameter :: HEIGHT = 3
! ...
integer, parameter :: NUM_ENTRIES = 10
并分配类似的东西
allocate(elements(NUM_ENTRIES,10000))
所以我可以访问类似的元素
write(*,*) elements(WIDTH,100) ! gives the width of the 100th element
现在我不仅想要整数,还想要每个元素的混合类型。 所以我定义了一个派生类型
type Element
logical active
integer type
real width
! etc
end type
并使用元素数组
type(Element), allocatable :: elements(:)
对于二维数组版本,我可以调用一个子例程来告诉它使用哪个条目。 例如
subroutine find_average(entry, avg)
integer, intent(in) :: entry
real, intent(out) :: avg
integer i,
real s
s = 0
do i = lbound(elements,1), ubound(elements,1)
if (elements(TYP,i) .gt. 0) s = s + elements(entry,i)
end do
avg = s/(ubound(elements,1)-lbound(elements,1))
end subroutine
因此我可以调用 find_average(HEIGHT)
来查找平均高度或传递 WIDTH
来获取平均宽度。
(我的子例程比查找平均高度或宽度做更高级的事情,这只是一个例子。)
问题:如何使用不同的类型(如派生类型),同时重用我的函数来处理不同的条目(如示例子例程)?
最佳答案
对于数组情况,您可以传入单个参数数组 (i),而不是传入参数数组和索引 i。当您切换到具有派生类型时,类似地,您可以传入 variable_of_type % 元素,而不是传入整个 variable_of_type 并以某种方式指示过程它应该处理哪个子元素。如果不同类型的元素(例如,逻辑、整数、实数)的代码需要不同,那么您可以为每个元素编写特定的过程,然后通过通用接口(interface) block 使用通用名称调用。编译器必须能够通过参数的某些特征(这里是它们的类型)来区分通用接口(interface) block 的过程。有关区分特征为数组等级的代码示例,请参见 how to write wrapper for 'allocate'
编辑:示例代码。这是否符合您的要求?
module my_subs
implicit none
interface my_sum
module procedure sum_real, sum_int
end interface my_sum
contains
subroutine sum_real (array, tot)
real, dimension(:), intent (in) :: array
real, intent (out) :: tot
integer :: i
tot = 1.0
do i=1, size (array)
tot = tot * array (i)
end do
end subroutine sum_real
subroutine sum_int (array, tot)
integer, dimension(:), intent (in) :: array
integer, intent (out) :: tot
integer :: i
tot = 0
do i=1, size (array)
tot = tot + array (i)
end do
end subroutine sum_int
end module my_subs
program test_dt
use my_subs
implicit none
type my_type
integer weight
real length
end type my_type
type (my_type), dimension (:), allocatable :: people
type (my_type) :: answer
allocate (people (2))
people (1) % weight = 1
people (1) % length = 1.0
people (2) % weight = 2
people (2) % length = 2.0
call my_sum ( people (:) % weight, answer % weight )
write (*, *) answer % weight
call my_sum ( people (:) % length, answer % length )
write (*, *) answer % length
end program test_dt
关于arrays - 派生类型数组 : select entry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9847117/