Log in

View Full Version : Way to copy TPA...



bg5
05-13-2012, 12:42 PM
I have trouble with copying TPA...

program new;
var
tpa1 ,tpa2 : TPointArray;
a ,b :integer;
begin
tpa1 := [Point(1,1),Point(2,2) ];
tpa2 := tpa1;
OffsetTPA(tpa2,Point(2,2));

writeln(tpa1);
writeln(tpa2);

a := 2;
b := a;
b := 3;
writeln(a);
writeln(b);
end.


[(3, 3), (4, 4)]
[(3, 3), (4, 4)]
2
3

As you see tpa2 := tpa1; doesn't copy tpa1 to tpa2 ,but copy tpa1's pointer...differently then with simple types. There is already function CopyTPA ,but it's leaking and don't have wrapper , so I won't use it ,because I want to do this operation very frequently. Only possible way I see is iteration ,but it will slow down my script.
Iteration I mean:
hi := high(tpa1);
SetLength(tpa2,hi+1);
for a:=0 to hi do
tpa2[a] := tpa1[a];
any ideas?

Runaway
05-13-2012, 12:56 PM
I messed around with it for a bit, and this seems to be the only way I can find that works:


program new;
var
tpa1 ,tpa2 : TPointArray;
begin
tpa1 := [Point(1,1), Point(2,2)];
AppendTPA(tpa2, tpa1);
OffsetTPA(tpa2, Point(2,2));

writeln(tpa1);
writeln(tpa2);
end.


it outputs:



[(1, 1), (2, 2)]
[(3, 3), (4, 4)]


E: there are obvious downfalls to this, but it looks like it should work as long as the second TPA is empty.

nielsie95
05-13-2012, 12:59 PM
a := b;
l := Length(a);
SetLength(b, l + 1);
SetLength(b, l);

Brandon
05-13-2012, 01:34 PM
Result:= CopyTPA(TPA);

bg5
05-13-2012, 02:10 PM
I messed around with it for a bit, and this seems to be the only way I can find that works:


program new;
var
tpa1 ,tpa2 : TPointArray;
begin
tpa1 := [Point(1,1), Point(2,2)];
AppendTPA(tpa2, tpa1);
OffsetTPA(tpa2, Point(2,2));

writeln(tpa1);
writeln(tpa2);
end.


it outputs:



[(1, 1), (2, 2)]
[(3, 3), (4, 4)]


E: there are obvious downfalls to this, but it looks like it should work as long as the second TPA is empty.

Thanks it's what I'm looking for. I will add tpa2:=[]; to make sure it's empty.

a := b;
l := Length(a);
SetLength(b, l + 1);
SetLength(b, l);

I have no idea ,how it works ,but it's nice too:)


Result:= CopyTPA(TPA);

It's leaking.

Brandon
05-13-2012, 02:30 PM
Function CopyTPAX(StartIndex, EndIndex: Integer; TPAToCopy: TPointArray): TPointArray;
var
I: Integer;
TPA: TPointArray;
begin
SetLength(TPA, iAbs(EndIndex - StartIndex) + 1);
For I:= StartIndex To EndIndex do
begin
TPA[I]:= TPAToCopy[I];
end;
Result:= TPA;
end;

var
TPA, T: TPointArray;
begin
TPA:= [Point(1, 2), Point(3, 4), Point(4, 6)];

T:= CopyTPAX(0, High(TPA), TPA);
writeln(T);
end.

masterBB
05-13-2012, 02:33 PM
Small fix ;)

Function CopyTPAX(StartIndex, EndIndex: Integer; TPAToCopy: TPointArray): TPointArray;
var
I: Integer;
TPA: TPointArray;
begin
SetLength(TPA, iAbs(EndIndex - StartIndex) + 1);
For I:= StartIndex To EndIndex do
begin
TPA[I-StartIndex]:= TPAToCopy[I];
end;
Result:= TPA;
end;