www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 473] New: Arrays should have a way to take out an element or slice

reply d-bugmail puremagic.com writes:

           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 digitalmars.com
        ReportedBy: wbaxter 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:

// 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
    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];


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.

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.

Oct 31 2006
parent d-bugmail puremagic.com writes:

Andrei Alexandrescu <andrei metalanguage.com> changed:

           What    |Removed                     |Added
             Status|NEW                         |RESOLVED
                 CC|                            |andrei metalanguage.com
         Resolution|                            |FIXED

--- Comment #1 from Andrei Alexandrescu <andrei metalanguage.com> 2010-09-25
18:15:45 PDT ---
std.algorithm.remove implements the needed functionality.

Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Sep 25 2010