Bug 473 – Arrays should have a way to take out an element or slice
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D1 (retired)
Platform
All
OS
All
Creation time
2006-10-31T17:51:00Z
Last change time
2014-02-15T13:27:16Z
Assigned to
nobody
Creator
wbaxter
Comments
Comment #0 by wbaxter — 2006-10-31T17:51:29Z
There should be a simple way to efficiently remove/drop/erase an element or slice from anywhere in an array.
David Medlock proposes this function for taking out one element:
(http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D.learn&artnum=5077)
// remove an item from an array
template drop(T)
{
T drop( inout T[] arr, int which )
{
debug if ( which>=arr.length)
throw new Exception(str.format("Attempt to drop position %s from size %s",which,arr.length));
T result = arr[which];
int max = arr.length-1;
for (; which < max; which++ ) arr[which]=arr[which+1];
arr.length= max;
return result;
}
}
Which Chris Nicholson-Sauls timed to be significantly faster than the alternative using slices:
a = a[0..n] ~ a[n+1..length];
(http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D.learn&artnum=5099)
A generalization of David's function to drop a range is straightforward.
Sean Kelly proposed it might be worth trying out an implementation using memmove instead of a loop.
(http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D.learn&artnum=5100)
A good syntax for this may be to mimick associative arrays, and use "remove()".
int[] a = [0,1,2,3,4,5];
a.remove(3); // a now [0,1,2,4,5]
a.remove(0,3); // a now [4,5]
An alternative, more integrated syntax would be to allow the use of assignment of void. Then slice syntax could be used directly.
a[2..4] = void; // removes a[2] and a[3]
This would require some modification of opSlice methods, or introduction of new ones, like opIndexRemove, opSliceRemove.
Comment #1 by andrei — 2010-09-25T18:15:45Z
std.algorithm.remove implements the needed functionality.