使用pack函数输出数组中满足条件元素的索引

发布时间 2023-12-27 11:43:38作者: 搬砖的鹏
program main_test

    implicit none
   
    real, dimension(5) :: arr1, arr2
    LOGICAL, dimension(5) :: ad, ab, ac, tot
    INTEGER , dimension(:), allocatable:: arr3
    INTEGER :: i
    arr1 = [1.0,2.3,-0.5,3.3,-1.6]
    arr2 = [1.0,-5.3,-0.5,-3.0,-1.6]
    ab = arr1 < 4
    ad = arr1 > 2
    ac = arr2 < 0
   
    tot = ad .and. ab .and. ac
    allocate(arr3(size(tot)))
    arr3 = pack([(i,i=1,5)],tot)
    print *, tot, 'size(tot)=', size(tot)
    print *, 'indices:', arr3
    print *, 'size:', size(arr3)
end program main_test

输出结果:

F T F T F size(tot)= 5
indices: 2 4
size: 2

动态数组会根据实际传递的数组大小调整动态数组大小。但是当声明静态数组arr3数组的大小为5的话,indices的输出结果会是这样的:

indices:           2           4         160           0  1211325946

后面3个数字应该是空的数组自动生成的元素。