lyb*_*rko 10 arrays delphi concatenation
是否有任何简单的通用方法将2个数组添加到一个?在下面的情况下,不可能简单地使用C := A + B
声明...我想避免每次都为它做算法.
TPerson = record
Birthday: Tdate;
Name, Surname:string;
end;
Tpeople = array of TPerson;
var A, B, C:Tpeople;
C:=A+B; // it is not possible
Run Code Online (Sandbox Code Playgroud)
感谢名单
Arn*_*hez 11
由于string
每个TPerson
记录中的两个字段,您不能只使用二进制"移动",因为您将搞乱引用计数string
- 特别是在多线程环境中.
你可以手动完成 - 这是快速和好的:
TPerson = record
Birthday: TDate;
Name, Surname: string;
end;
TPeople = array of TPerson;
var A, B, C: TPeople;
// do C:=A+B
procedure Sum(const A,B: TPeople; var C: TPeople);
begin
var i, nA,nB: integer;
begin
nA := length(A);
nB := length(B);
SetLength(C,nA+nB);
for i := 0 to nA-1 do
C[i] := A[i];
for i := 0 to nB-1 do
C[i+nA] := B[i];
end;
Run Code Online (Sandbox Code Playgroud)
或者你可以使用我们的TDynArray
包装器,它有一个处理这种情况的方法:
procedure AddToArray(var A: TPeople; const B: TPeople);
var DA: TDynArray;
begin
DA.Init(TypeInfo(TPeople),A);
DA.AddArray(B); // A := A+B
end;
Run Code Online (Sandbox Code Playgroud)
该AddArray
方法可以添加原始数组的子端口:
/// add elements from a given dynamic array
// - the supplied source DynArray MUST be of the same exact type as the
// current used for this TDynArray
// - you can specify the start index and the number of items to take from
// the source dynamic array (leave as -1 to add till the end)
procedure AddArray(const DynArray; aStartIndex: integer=0; aCount: integer=-1);
Run Code Online (Sandbox Code Playgroud)
请注意,对于此类记录,它将使用System._CopyRecord
RTL函数,该函数未针对速度进行优化.我写了一个更快的版本 - 请参阅此博客文章或此论坛帖子.
如果在函数/过程中使用动态数组,请不要忘记使用显式const
或var
参数(如上所述),否则它将在每次调用时生成临时副本,因此可能很慢.