Determine variable names dynamically according to a string in Fortran

后端 未结 4 1619
春和景丽
春和景丽 2020-12-02 02:26

I want to create a dynamic variable name using Fortran.

The variable name will be obtained by concatenating a string and another string/integer. Then I want to us

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 03:13

    I think you want to use a data structure. If you have pairs or groups of values that go together, then create a derived data type which can hold both. There's an explanation on this page:

    http://web.mse.uiuc.edu/courses/mse485/comp_info/derived.html

    If you have a list of these pairs (like your string and int above), then you can create an array of these types. Example code below taken from the page linked above:

    type mytype
       integer:: i
       real*8 :: a(3)
    end type mytype
    
    type (mytype) var
    

    Array:

    type (mytype) stuff(3)
    
    var%i = 3
    var%a(1) = 4.0d0
    stuff(1)%a(2) = 8.0d0
    

    An significant benefit of doing this is that you can pass the pairs/groups of items to functions/subroutines together. This is an important programming principle called Encapsulation, and is used extensively in the Object Oriented programming paradigm.

提交回复
热议问题