Assign to Array Column

Paul Backus snarwin at gmail.com
Thu Feb 2 05:47:34 UTC 2023


On Tuesday, 31 January 2023 at 01:04:41 UTC, Paul wrote:
> Greetings,
>
> for an array byte[3][3] myArr, I can code myArr[0] = 5 and have:
> 5,5,5
> 0,0,0
> 0,0,0
>
> Can I perform a similar assignment to the column?  This, 
> myArr[][0] = 5, doesn't work.
>
> Thanks!

Here's a solution using standard-library functions:

     import std.range: transversal;
     import std.algorithm: map, fill;
     import std.stdio: writefln;

     void main()
     {
         byte[3][3] myArr;
         myArr[]
             .map!((ref row) => row[])
             .transversal(0)
             .fill(byte(5));
         writefln("%(%s\n%)", myArr[]);
     }

The only tricky part here is the call to `map`, which is 
necessary to change the type of the rows from `byte[3]` (which is 
not a range type) to `byte[]` (which is one).

Once we've done that, `transversal(0)` lets us iterate over the 
items at index 0 in each row (in other words, over the first 
column), and `fill` sets each of those items to the specified 
value.

By the way, if we use Godbolt to look at the generated code, we 
can see that LDC with optimizations enabled compiles this very 
efficiently--it is able to inline all the range functions and 
unroll the loop:

https://d.godbolt.org/z/orernGc9b


More information about the Digitalmars-d-learn mailing list