[Issue 473] New: Arrays should have a way to take out an element or slice
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Oct 31 15:51:30 PST 2006
http://d.puremagic.com/issues/show_bug.cgi?id=473
Summary: Arrays should have a way to take out an element or slice
Product: D
Version: 0.172
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: bugzilla at digitalmars.com
ReportedBy: wbaxter at gmail.com
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.
--
More information about the Digitalmars-d-bugs
mailing list