filling an array of structures
Steven Schveighoffer
schveiguy at yahoo.com
Tue Jan 11 05:33:05 PST 2011
On Tue, 11 Jan 2011 00:39:55 -0500, Brad
<brad.lanam.comp_nospam at nospam_gmail.com> wrote:
> Given an array of structures that you need to populate.
> Also assume the structure is quite large and has many
> elements to fill in.
>
> S s[];
> while (something) {
> s.length += 1;
> auto sp = &s[$-1]; // method 1
> sp.a = 1;
> ...
> with (s[$-1]) { // method 2
> a = 1;
> }
> ...
> foreach (ref sp; s[$-1..$]) { // method 3
> sp.a = 1;
> }
> }
>
> I don't mind 'with' statements, but they have a readability and
> maintenance problem if their scope is large. The reader would have
> to be aware of the context of the structure and the local variables,
> whereas 'sp.a' is self documenting.
>
> method 3 is fine, and provides me with a reference to s[$-1],
> but I'd really like to have:
> auto sp = ref s[$-1]; // possible method 4
> where sp is a reference, but no pointer arithmetic can be done on it.
>
> Another alternative would be runtime aliases.
> alias s[$-1] as sp;
> Or
> sp = with (s[$-1]); // I don't much like this syntax...
>
> In the meantime, I'll go with method 1.
What about:
S sp;
sp.a = 1;
s ~= sp;
Or if you have a constructor for S, or a is the only member in it:
s ~= S(1);
-Steve
More information about the Digitalmars-d
mailing list