D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 473 - Arrays should have a way to take out an element or slice
Summary: Arrays should have a way to take out an element or slice
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D1 (retired)
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2006-10-31 17:51 UTC by Bill Baxter
Modified: 2014-02-15 13:27 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Bill Baxter 2006-10-31 17:51:29 UTC
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 Andrei Alexandrescu 2010-09-25 18:15:45 UTC
std.algorithm.remove implements the needed functionality.