如何保存派生类型成员的值(每次迭代中的值)?

时间:2019-04-24 12:11:39

标签: fortran gfortran intel-fortran

我不是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'。 有办法吗?

1 个答案:

答案 0 :(得分:0)

我建议使用可分配属性和move_alloc。这是一个示例程序。 move_alloc是Fortran2003。在此示例中,每次超过数组大小时,我都会增加其大小。

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