Add elements to the integer vector in chunks.
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer, | intent(inout), | dimension(:), allocatable | :: | vec | ||
integer, | intent(inout) | :: | n |
counter for last element added to |
||
integer, | intent(in) | :: | chunk_size |
allocate |
||
integer, | intent(in), | optional | :: | val |
the value to add to |
|
logical, | intent(in), | optional | :: | finished |
set to true to return |
pure subroutine expand_vector(vec,n,chunk_size,val,finished) implicit none integer,dimension(:),allocatable,intent(inout) :: vec integer,intent(inout) :: n !! counter for last element added to `vec`. !! must be initialized to `size(vec)` !! (or 0 if not allocated) before first call integer,intent(in) :: chunk_size !! allocate `vec` in blocks of this size (>0) integer,intent(in),optional :: val !! the value to add to `vec` logical,intent(in),optional :: finished !! set to true to return `vec` !! as its correct size (`n`) integer,dimension(:),allocatable :: tmp !! temporary array if (present(val)) then if (allocated(vec)) then if (n==size(vec)) then ! have to add another chunk: allocate(tmp(size(vec)+chunk_size)) tmp(1:size(vec)) = vec call move_alloc(tmp,vec) end if n = n + 1 else ! the first element: allocate(vec(chunk_size)) n = 1 end if vec(n) = val end if if (present(finished)) then if (finished) then ! set vec to actual size (n): if (allocated(tmp)) deallocate(tmp) allocate(tmp(n)) tmp = vec(1:n) call move_alloc(tmp,vec) end if end if end subroutine expand_vector