加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

有没有办法将2个数组添加到一个?

发布时间:2020-12-15 04:28:41 所属栏目:大数据 来源:网络整理
导读:有没有任何简单的统一的方法来添加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 i
有没有任何简单的统一的方法来添加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

感谢名单

解决方法

由于每个TPerson记录中的两个字符串字段,您不能仅仅使用二进制“move”,因为您会混淆字符串的引用计数,特别是在多线程环境中.

你可以手动做 – 这是快速和美好的:

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

TPeople = array of TPerson;

var A,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 article或this forum thread.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读