how to append (ref) int[] to int[][]?
Dukc
ajieskola at gmail.com
Mon Jun 8 11:52:50 UTC 2020
On Monday, 8 June 2020 at 06:13:36 UTC, mw wrote:
>
> what I really want in (a) is append `ref arr` and output [[3],
> [3], [3]], i.e. the real `arr` be appended instead of its copy.
>
> I tried to change arrs' decl to:
>
> (ref (int[]))[] arrs; // the intended semantics I want
>
> 1) I'm wondering how to achieve what I want? and
> 2) why "~=" here will append a copy rather than the real `arr`
> itself to arrs?
>
>
> Thanks.
```
import std.stdio;
void f(ref int[] arr) {
arr ~= 3;
}
void main() {
import std.algorithm;
int[]*[] arrs;
int[]* arr;
foreach (i; 0 .. 3) {
//stack allocated array pointer&length would expire on end of
scope, so must allocate the them on heap since we're keeping
refeerences on them.
auto arrayAllocation = new int[][1];
arr = &arrayAllocation[0];
*arr = new int[0];
arrs ~= arr;
f(*arr);
}
//will print an array of addresses otherwise
arrs.map!(ptr => *ptr).writeln;
}
```
But I must say I would generally prefer just calling `f()` on
`arrs[i]` directly after appending, or calling the function
before appending. One reason is that needless heap usage is
generally less efficient than using the stack.
More information about the Digitalmars-d-learn
mailing list