attribute length missing in std.array: Appender

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 28 16:12:06 PST 2014


On 11/28/2014 12:44 AM, bearophile wrote:

 > Now we have a better syntax for implicit casts:

[...]

 >      app.put(ubyte(0).repeat.take(5));

Much better! :)

 > But I have a question too. What's the best way to append several lazy
 > items to a dynamic array? This doesn't work:
 >
 > void main() {
 >      import std.array, std.range;
 >      int[] arr;
 >      arr.put(only(1, 2, 3));
 > }

I don't think there is a better way in Phobos. (?) The following trivial 
function would do as long as the array has room at the end, which 
requires that it is "safe to append":

void expandWith(A, R)(ref A arr, R range)
{
     foreach (e; range) {
         arr ~= e;
     }
}

void main() {
     import std.range;

     int[] arr = [ 42 ];

     // Ensure that there is room for new elements
     arr.reserve(100);
     assumeSafeAppend(arr);

     const oldPlace = arr.ptr;
     arr.expandWith(only(1, 2, 3));
     const newPlace = arr.ptr;

     assert(newPlace == oldPlace);
}

Ali



More information about the Digitalmars-d-learn mailing list