问题
Is there a function in Fortran that deletes a specific element in an array, such that the array upon deletion shrinks its length by the number of elements deleted?
Background: I'm currently working on a project which contain sets of populations with corresponding descriptions to the individuals (i.e, age, death-age, and so on).
A method I use is to loop through the array, find which elements I need, place it in another array, and deallocate the previous array and before the next time step, this array is moved back to the array before going through the subroutines to find once again the elements not needed.
回答1:
You can use the PACK intrinsic function and intrinsic assignment to create an array value that is comprised of selected elements from another array. Assuming array
is allocatable, and the elements to be removed are nominated by a logical mask logical_mask
that is the same size as the original value of array
:
array = PACK(array, .NOT. logical_mask)
Succinct syntax for a single element nominated by its index is:
array = [array(:index-1), array(index+1:)]
Depending on your Fortran processor, the above statements may result in the compiler creating temporaries that may impact performance. If this is problematic then you will need to use the subroutine approach that you describe.
回答2:
Maybe you want to look into linked lists. You can insert and remove items and the list automatically resizes. This resource is pretty good. http://www.iag.uni-stuttgart.de/IAG/institut/abteilungen/numerik/images/4/4c/Pointer_Introduction.pdf
回答3:
To continue the discussion, the solution you might want to implement depends on the number of delete operation and access you do, where you insert/delete the elements (the first, the last, randomly in the set?), how do you access the data (from the first to the last, randomly in the set?), what are your efficiency requirements in terms of CPU and memory. Then you might want to go for linked list or for static or dynamic vectors (other types of data structures might also fit better your needs).
For example:
- a static vector can be used when you want to access a lot of elements randomly and know the maximum number
nmax
of elements in the vector. Simply use an array ofnmax
elements with an associatedlength
variable that will track the last element. A deletion can simply and quickly be done my exchanging the last element with the deleted one and reducing the length. - a dynamic vector can be implemented when you don't know the maximum number of elements. In order to avoid systematic array allocation+copy+unallocation at for each deletion/insertion, you fix the maximum number of elements (as above) and only augment its size (eg.
nmax
becomes10*nmax
, then reallocate and copy) when reaching the limit (the reverse system can also be implemented to reduce the number of elements).
来源:https://stackoverflow.com/questions/36561018/delete-a-specific-element-from-a-fortran-array