append an entry to an allocatable array 1d with single integer at the end If the array is too small, reallocate with double size
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer(kind=int_k), | intent(inout), | allocatable | :: | Array(:) |
array to append value to |
|
integer(kind=int_k), | intent(in) | :: | Value |
The value to add as an entry in Array |
||
integer, | intent(inout) | :: | nElems |
Number of entries in the array (changes, if added = .true.) |
||
integer, | intent(out) | :: | Pos |
position the value was appended |
||
logical, | intent(out) | :: | Added |
new entry in array added? |
subroutine tem_appendInt1dArrayUnique( Array, Value, nElems, Pos, Added )
! ---------------------------------------------------------------------------
!> array to append value to
integer(kind=int_k),intent(inout), allocatable :: Array(:)
!> The value to add as an entry in Array
integer(kind=int_k),intent(in) :: Value
!> Number of entries in the array (changes, if added = .true.)
integer,intent(inout) :: nElems
!> position the value was appended
integer,intent(out) :: Pos
!> new entry in array added?
logical,intent(out) :: Added
! ---------------------------------------------------------------------------
integer,allocatable :: tempArray(:)
integer :: ArraySize,ierr,NewSize, iPos
logical :: found !< has the new entry been found in the existing list?
! ---------------------------------------------------------------------------
added = .false.
found = .false.
! Get size of array
ArraySize = size(Array,1)
if( ArraySize .gt. 0) then
! check if value already exists
do iPos = 1, nElems
if(Array(iPos) .eq. Value ) then
found = .true.
Pos = iPos
endif
enddo
if(.not. found) then ! Add to array
nElems = nElems + 1
if ( nElems .gt. ArraySize ) then ! Resize array
NewSize = ArraySize*2
allocate(tempArray(NewSize),stat=ierr)
! Copy to temp array
tempArray(1:ArraySize) = Array(1:ArraySize)
! Deallocate Array
deallocate(Array)
! Reallocate Array
allocate(Array(NewSize),stat=ierr)
Array(1:ArraySize) = tempArray(1:ArraySize)
! Deallocate temp array
deallocate(tempArray)
if(ierr .ne. 0) Write(*,*) 'Error in reallocating array'
endif
Array( nElems ) = Value
added = .true.
Pos = nElems
endif ! not found yet
else ! size zero. reallocate and add value.
deallocate( Array )
allocate(Array( InitialSize ))
nElems = 1
Array( nElems ) = Value
added = .true.
Pos = nElems
endif
end subroutine tem_appendInt1dArrayUnique