Fastest Way to Append Multiple Elements to an Array

zeljkog via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 17 05:30:47 PST 2014


On 17.12.14 13:30, Tobias Pankrath wrote:
> void append(T, Args...)(ref T[] data, Args args)
> {
>      static size_t estimateLength(Args args)
>      {
>          size_t result;
>          foreach(e; args)
>              static if(hasLength!(typeof(e)))
>                  result += e.length;
>              else
>                  result += 1;
>
>          return result;
>      }
>
>      auto app = appender!(T[])(data);
>      app.reserve(data.length + estimateLength(args));
>
>      foreach(e; args)
>          app.put(e);
>      data = app.data;
> }
>
> void main()
> {
>      import std.stdio;
>      int[] data;
>      append(data, 1, 2, only(1, 2, 3), iota(4, 9));
>      writeln(data);
> }
>
> ---
>
> Maybe appender.put should get an overload that does the same, though I
> didn't had the need for it yet.

It's for convenient one line: arr.append(e1, e2, ...);
I said "something like that" :)


More information about the Digitalmars-d-learn mailing list