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

标签 arrays delphi concatenation

是否有任何简单的通用方法可以将两个数组添加到一个数组中?在下面的情况下,不可能简单地使用 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/

相关文章:

delphi - 如何自动滚动到 RichEdit 的末尾?

arrays - Swift 数组中的 CGFloat

javascript - Angular ng-repeat 不适用于我的数组

java - 如何在 android studio 中找到数组中项目的编号?

string - Go中字符串变量的连接速度

ios - 如何在 iOS 中将三个文本文件的数据连接/合并为一个文本文件

c - strcat() 在尝试创建以空格分隔的字符串时删除字符串。 (C 编程)

java - 使用堆栈反转数组

delphi - 泛型、接口(interface)和继承的问题

delphi - Indy 10 中的 TIdHTTP