简短的回答是“否”,Fortran 中没有这样的intrinsic 函数。
通常希望您自己编写类似的内容。例如:
- 从所有可能的起始索引的数组开始
- 确定保持索引的条件
- 依次只保留满足条件的索引
内在过程pack 在这里非常有用,它可用于仅保留数组(您的起始位置)中匹配特定条件(您保持起始位置的条件)的值。
下面的(未经广泛测试!)程序“test.f90”说明了用法:
module mod_finder
implicit none
contains
subroutine find_start_locs(array, sub_array, start_locs)
integer, intent(in) :: array(:)
integer, intent(in) :: sub_array(:)
integer, allocatable, intent(out) :: start_locs(:)
integer :: i
! initialize result with all possible starting indices
start_locs = [(i, i = 1, size(array)-size(sub_array)+1)]
! sequentially keep only those indices that satisfy a condition
do i = 1, size(sub_array)
! condition for keeping: the value of array(start_locs + i - 1) must be equal to the value of sub_array(i)
! use PACK to only keep start_locs that satisfy this condition
start_locs = PACK(start_locs, array(start_locs + i - 1) == sub_array(i))
if (size(start_locs) == 0) then
exit
end if
end do
end subroutine find_start_locs
end module mod_finder
program test
use mod_finder
implicit none
integer, allocatable :: arr(:)
integer, allocatable :: seq(:)
integer, allocatable :: res(:)
! arr = [1, 5, 8, 56, 33, 56, 78, 123, 78, 8, 34, 33, 19, 25, 36]
arr = [1, 5, 8, 56, 33, 56, 78, 123, 78, 8, 56, 33, 19, 25, 36]
seq = [8, 56, 33]
call find_start_locs(arr, seq, res)
print *, "array: ", arr
print *, "sequence: ", seq
print *, "locations: ", res
print *, "# matches: ", size(res)
end program test
对于您问题中的两个测试用例,编译和运行会给出以下输出:
$ gfortran -O2 -g -Wall -Wextra -fcheck=all test.f90
$ ./a.out
array: 1 5 8 56 33 56 78 123 78 8 34 33 19 25 36
sequence: 8 56 33
locations: 3
# matches: 1
和
array: 1 5 8 56 33 56 78 123 78 8 56 33 19 25 36
sequence: 8 56 33
locations: 3 10
# matches: 2