Squaring Arrays without Overlapping Array Error

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 7 06:51:32 PDT 2015


On Tuesday, 7 July 2015 at 08:06:50 UTC, tcak wrote:
>
> I have never used arrays in that way before, though I don't get 
> why you are writing return line in that way. Shouldn't it be 
> like `return (x[] * x[]);` ?


There's nothing fundamentally wrong with doing that in the return 
line. For instance, the one I duplicated the array on looks like

int[] square_array_dup(int[] x)
{
	auto y = x.dup;
	return y[] *= x[];
}

To get your way to work requires

int[] square_array(int[] x)
{
	int[] y;
	y.length = x.length;
	y[] = x[] * x[];
	return y;
}

which can be slower.

Anyway, the main reason I used x[] *= x[] was that the original 
code I had written was not in a function and was just

void main()
{
	int len = 10;
	auto x = len.iota.array;
	x[] *= x[];
}

Obviously, in this case, I can just do a map before putting it 
into an array, but then I got more interested in squaring arrays.


More information about the Digitalmars-d-learn mailing list