gpt4 book ai didi

arrays - 有什么办法可以将2个数组添加到一个数组中吗?

转载 作者:行者123 更新时间:2023-12-03 14:41:21 25 4
gpt4 key购买 nike

是否有任何简单的通用方法可以将两个数组添加到一个数组中?在下面的情况下,不可能简单地使用 C := A + B 语句...我想避免每次都为它制作algorhytm。

TPerson = record
Birthday: Tdate;
Name, Surname:string;
end;

Tpeople = array of TPerson;

var A, B, C:Tpeople;

C:=A+B; // it is not possible

谢谢

最佳答案

由于两个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;

或者您可以使用我们的 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;

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);

请注意,对于此类记录,它将使用 System._CopyRecord RTL 函数,其速度并没有那么优化。我写了一个更快的版本 - 请参阅 this blog articlethis forum thread .

如果您在函数/过程中使用动态数组,请不要忘记显式使用 constvar参数(如我上面编码的),否则它将在每次调用时进行临时复制,因此可能会很慢。

关于arrays - 有什么办法可以将2个数组添加到一个数组中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7102887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com