len*_*nho 4 arrays fortran derived-types
我想使用子例程 sum_real 访问数组派生类型中数组的元素。即:对所有人的权重中的第一个条目求和。
type my_type
real, dimension(:), allocatable :: weight
real :: total_weight
end type my_type
type (my_type), dimension (:), allocatable :: people
type (my_type) :: answer
allocate (people (2))
allocate (people (1)%weight(2))
allocate (people (2)%weight(2))
people (1) % weight(1) = 1
people (2) % weight(1) = 1
people (1) % weight(2) = 3
people (2) % weight(2) = 3
call sum_real ( people (:) % weight(1), answer % total_weight )
Run Code Online (Sandbox Code Playgroud)
我想要做的类似于在派生类型数组中找到的答案:select entry,除了我在数组派生类型而不是单个元素中分配了一个数组。
但是,我收到一个编译器错误:
error #7828: The part-name to the right of a part-ref with nonzero rank has the ALLOCATABLE attribute (6.1.2). [WEIGHT]
Run Code Online (Sandbox Code Playgroud)
如果您的组件是可分配的,则您尝试的操作是不可能的。引用(6.1.2)实际上是对官方标准文档的引用,禁止这样做。
原因很简单,可分配的组件(标量或数组)存储在与派生类型本身不同的内存部分。因此,如果你写
sum(people%total_weight)
Run Code Online (Sandbox Code Playgroud)
或者
people%total_weight = 0
Run Code Online (Sandbox Code Playgroud)
没问题,total_weight不可分配,它存储在派生类型中,编译器只是进入一个简单的循环并将一个接一个字段设置为零。您可以%totalweight事先知道每个地址。
另一方面
sum(people%weight)
Run Code Online (Sandbox Code Playgroud)
或者
people%weight = 0
Run Code Online (Sandbox Code Playgroud)
each%weight存储在其他地方,您没有任何简单的公式来计算 each 的位置%weight(i)。
如果可能,解决方案是固定数组的大小
real, dimension(2) :: weight
Run Code Online (Sandbox Code Playgroud)
或使用 do 循环
s = 0
do i = 1, size(people)
S = S + sum(people(i)%weight)
end do
Run Code Online (Sandbox Code Playgroud)
如果您有 F2003 编译器,并且组件数组的边界对于特定的父数组对象是相同的,则通过常量表达式指定的大小的第三种方法/使用 VladimirF 指定的 do 循环方法是参数化类型。
type my_type(n) ! This type has one parameter - n
integer, len :: n ! The parameter n is a length parameter.
real :: weight(n) ! This component depends on that parameter.
end type my_type
type (my_type(:)), dimension(:), allocatable :: people
! This integer is the size of the people component. Because
! people is allocatable it can be determined at runtime.
number_of_people = 2
! This integer is the size of the weight component that we want
! in the array people. Other arrays and scalars of type
! my_type can have different sizes for that component.
! Because people is allocatable this can be determined at
! runtime.
number_of_weights = 2
allocate( my_type(number_of_weights) :: people(number_of_people) )
! Define people%weight here.
people(1)%weight(1) = 1
...
! Using sum intrinsic for the sake of example
do i = 1, people%n
! The argument to sum is an array section.
print *, sum(people%weight(i))
! ^ ^ Reference to an element of a component
! | Reference to the entire people array
end do
Run Code Online (Sandbox Code Playgroud)
参数化类型数组中的每个元素都具有相同的类型参数,因此中的每个weight组件都people具有相同的边界,因此诸如此类的引用people%weight变为“常规”。
使用这种方法(或恒定组件大小规范方法)的代码仍然必须遵循对组件引用的限制,即只有引用的一部分可以具有非零等级(您不能people%weight作为一个整体处理人和重量分量的等级为 1)。
在可分配组件的情况下,某些元素中的某些组件可能不会被分配,并且它们被分配的位置可能具有不同的边界,这使得在概念上难以跨数组元素对组件中的数据进行“常规”引用。
| 归档时间: |
|
| 查看次数: |
1526 次 |
| 最近记录: |