Creating an array of default-constructed class instances

Ali Çehreli acehreli at yahoo.com
Sat Feb 9 22:52:56 PST 2013


On 02/09/2013 10:14 PM, Simon wrote:
 > Hi, I'm new to the D programming language. Overall I'm liking
 > things very much, but I'm still getting the hang of a few things.
 >
 > Here's a basic programming pattern: I have a class called Thing,
 > and while I'm coding I decide I need N Thing instances.
 >
 > In C++ that's a matter of
 >
 > std::vector<Thing> things(N);
 >
 > In python, I can use a list comprehension.
 >
 > things = [Thing() for _ in range(N)]
 >
 > However, the obvious D version doesn't work.
 >
 > auto things = new Thing[N];
 >
 > Because Thing.init is null, this produces an array of null
 > references. Of course, I can write a for loop to fill in the
 > array after creation, but this feels very un-D-like. Is there a
 > straightforward way to create a bunch of class instances?

Here is one way:

import std.stdio;
import std.range;
import std.algorithm;

class Thing
{
     int i;

     this(int i)
     {
         this.i = i;
     }
}

void main()
{
     auto things = iota(10).map!(i => new Thing(i))().array;
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list