fast way to insert element at index 0

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 22 23:01:44 PDT 2015


On 06/22/2015 10:16 PM, Assembly wrote:> What's a fast way to insert an 
element at index 0 of array? now that the
 > code is working I want to clean this:
 >
 > void push(T val)
 >      {
 >          T[] t = new T[buffer.length + 1];
 >          t[0] = val;
 >          t[1 .. $] = buffer;
 >          buffer = t;
 >      }
 >
 > I did this because I didn't find any suble built-in data structure that
 > let me insert an item into a specific index at first search. Slist does
 > have insertFron(), exactly what I'm looking for it's a linked list.

If the array is huge, you may find it to be faster to not move any data 
at all but treat both that single element and the array as one larger 
range. chain() does that:

import std.algorithm;
import std.range;

void main()
{
     auto arr = [ 0, 1, 2 ];
     auto singleElement = 42.only;
     auto both = chain(singleElement, arr);

     assert(both.equal([ 42, 0, 1, 2 ]));

     // Supports random access as well:
     assert(both[0] == 42);
     // ...
     assert(both[$-1] == 2);
}

As you can see, although what chain() returns is not an array, it is a 
RandomAccessRange; so, indexing works just fine. However, do test its 
performance before using it as some of its operations necessarily do 
more work than a real array (or slice).

Ali



More information about the Digitalmars-d-learn mailing list