Append to 'map' result
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 4 17:00:13 PDT 2017
On Tuesday, July 04, 2017 23:50:57 Nicholas Wilson via Digitalmars-d-learn
wrote:
> On Tuesday, 4 July 2017 at 23:27:25 UTC, Jean-Louis Leroy wrote:
> > I want to create a range that consists of the result of a map()
> >
> > followed by a value, e.g.:
> > int[] x = [ 1, 2, 3];
> > auto y = map!(x => x * x)(x);
> > auto z = y ~ 99; // how???
> >
> > I have tried several variations: convert 99 to a dynamic array,
> > to a range, convert range to dynamic array (couldn't even
> > figure that one); to no avail.
> >
> > Help please...
>
> using
> auto y = x.map!(x => x * x).array;
> will work.
Yeah, that will convert the range to a dynamic array, but if you're looking
to do is append onto a range, then using chain like H.S. Teoh showed is
better. And even if you ultimately want a dynamic array, using chain and
then calling array on the result than allocating the array and then
appending to it as an array means that you're only going to allocate the
array once, whereas if you append to the array, you might end up causing it
to be reallocated (though if you're just appending a single element to it
it'll have the space unless in std.array.array allocates a dynamic array
with exactly the space required for its elements, which I doubt).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list