Dynamic array and foreach loop

Jay Norwood via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 9 09:42:15 PDT 2015


On Sunday, 9 August 2015 at 15:37:23 UTC, Binarydepth wrote:
> So I should use the REF like this ?
>
> import std.stdio : writeln;
> void main()     {
>         immutable a=5;
>         int[a] Arr;
>         foreach(num; 0..a)      {
>                 Arr[num] = num;
>         }
>         foreach(num, ref ele; Arr)      {
>                 writeln(Arr[ele]+1);//Using the REF
>         }
> }

The reference v is to the array member in this case, rather than 
making a copy.  In the last loop c is a copy.  No big deal for 
this case of int Arr members, but if Arr was made up of struct 
members, you might not want to be making copies.

The i+3 initialization is just so you can see that v is the Arr 
member (not the index) in the other loops.

import std.stdio : writeln;
void main()     {
	immutable a=5;
	int[a] Arr;
	foreach(i, ref v; Arr)      {
		v = i+3;
	}
	foreach( ref v; Arr)      {
		writeln(v);
	}
	foreach( c; Arr)      {
		writeln(c);
	}
}



More information about the Digitalmars-d-learn mailing list