digitalmars.D.learn - foreach( i, e; a) vs ndslice
- Jay Norwood (31/31) Jan 18 2016 I'm playing with the example below. I noticed a few things.
- Ilya Yaroshenko (25/56) Jan 19 2016 Hi,
I'm playing with the example below. I noticed a few things. 1. The ndslice didn't support the extra index, i, in the foreach, so had to add extra i,j. 2. I couldn't figure out a way to use sliced on the original 'a' array. Is slicing only available on 1 dim arrays? 3. Sliced parameter order is different than multi-dimension array dimension declaration. import std.stdio; import std.experimental.ndslice.slice; void main() { int[4][5] a = new int[20]; foreach(i,ref r; a){ foreach(j,ref c; r){ c= i+j; writefln("a(%d,%d)=%s",i,j,c); } } writefln("a=%s",a); auto b = new int[20].sliced(5,4); int i=0; foreach( ref r; b){ int j=0; foreach( ref c; r){ c= i+j; writefln("b(%d,%d)=%s",i,j,c); j++; } i++; } writefln("b=%s",b); }
Jan 18 2016
On Monday, 18 January 2016 at 23:33:53 UTC, Jay Norwood wrote:I'm playing with the example below. I noticed a few things. 1. The ndslice didn't support the extra index, i, in the foreach, so had to add extra i,j. 2. I couldn't figure out a way to use sliced on the original 'a' array. Is slicing only available on 1 dim arrays? 3. Sliced parameter order is different than multi-dimension array dimension declaration. import std.stdio; import std.experimental.ndslice.slice; void main() { int[4][5] a = new int[20]; foreach(i,ref r; a){ foreach(j,ref c; r){ c= i+j; writefln("a(%d,%d)=%s",i,j,c); } } writefln("a=%s",a); auto b = new int[20].sliced(5,4); int i=0; foreach( ref r; b){ int j=0; foreach( ref c; r){ c= i+j; writefln("b(%d,%d)=%s",i,j,c); j++; } i++; } writefln("b=%s",b); }Hi, 1. You can use std.range.enumerate or just use a normal foreach: foreach(i; 0..slice.length!0) { /// use slice[i] ... } 2. Yes (A 2D D array is an array of arrays, so slice would be a slice composed of arrays) 3. Order is correct: void main() { auto a = new long[][](5, 4); auto b = new long[20].sliced(5, 4); foreach(i, ref r; a) { foreach(j, ref c; r) { c = i+j; b[i, j] = c; writefln("a(%d,%d)=%s", i, j, c); writefln("b(%d,%d)=%s", i, j, b[i, j]); } } writefln("a=%s",a); writefln("b=%s",b); } Ilya
Jan 19 2016