如何保存衍生类型成员的价值(来自每一次迭代)?

问题描述 投票:0回答:1

我在fortran中没有经验丰富的程序员,所以我需要一个关于我的简单代码的帮助。我的代码是:

module derived_type

implicit none

type :: iter_type

  integer :: calc_tmp
  integer :: n_iter

  contains

    procedure :: calc_iter     => calc_iter_process
    procedure :: take_calc_tmp => take_data_calc_tmp
    procedure :: take_n_iter   => take_data_n_iter

end type iter_type

private :: calc_iter_process
private :: take_data_calc_tmp
private :: take_data_n_iter

contains

function calc_iter_process( this, indx_00 ) result( err_tmp )

  class( iter_type )    :: this
  integer, intent( in ) :: indx_00
  logical               :: err_tmp

  err_tmp = .false.

  this%n_iter = 0

  this%calc_tmp = 1

  do while( this%calc_tmp < indx_00 )

    this%n_iter = this%n_iter + 1

    if ( this%n_iter > 50 ) then

      write(*,*) "error - maximal number of iterations !!!"
      err_tmp = .true.
      exit

    end if

    this%calc_tmp = this%calc_tmp + 1

  end do

end function calc_iter_process

function take_data_calc_tmp( this ) result( data_tmp )

  class( iter_type ) :: this
  integer            :: data_tmp

  data_tmp = this%calc_tmp

end function take_data_calc_tmp

function take_data_n_iter( this ) result( data_tmp )

  class( iter_type ) :: this
  integer            :: data_tmp

  data_tmp = this%n_iter

end function take_data_n_iter

end module derived_type

program iteration_values

use, non_intrinsic :: derived_type

implicit none

integer, parameter :: number_00 = 32
logical            :: global_err

type( iter_type ) :: iter_object

global_err = iter_object%calc_iter( number_00 )

if ( global_err ) stop "error - global !!!"

end program iteration_values

我需要找到代码修改的方法,它可以让我在每次迭代中保持或保存'calc_tmp'的值。当我想到这一点时,我无法想象如何分配或释放一些必须与'n_iter'相同或更高的数组。有没有办法做到这一点?

fortran gfortran intel-fortran
1个回答
0
投票

我建议使用allocatable属性和move_alloc。这是一个示例程序。 move_alloc是Fortran 2003.在这个例子中,每次超出它的大小时我都会增加数组的大小。

program temp

implicit none

integer, dimension(:), allocatable :: tempval, calc_tmp_history
integer :: i, j, calc_tmp, totalSize

totalSize = 0
allocate(calc_tmp_history(2))
do i = 1,4
    calc_tmp = 2*i
    if (i > size(calc_tmp_history)) then
        call move_alloc(calc_tmp_history,tempval)
        allocate(calc_tmp_history(2*i))
        do j = 1,i
            calc_tmp_history(j) = tempval(j)
        end do
    end if
    calc_tmp_history(i) = calc_tmp
    totalSize = totalSize + 1
end do

do i = 1,totalSize
    print *, calc_tmp_history(i)
end do
end program

这个输出是:

2
4
6
8
© www.soinside.com 2019 - 2024. All rights reserved.