有没有办法将2个阵列添加到一个? [英] Is any way to add 2 arrays into one?

查看:161
本文介绍了有没有办法将2个阵列添加到一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个简单的统一的方法来添加2个数组到一个?在下面的情况下,不可能简单地使用 C:= A + B 语句...
我想避免每次都使用它。 p>

Is there any simple univesal way to add 2 arrays into one? In the case below it is not possible simply use C := A + B statement... I would like to avoid making algorhytm for it everytime .

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

Tpeople = array of TPerson;

var A, B, C:Tpeople;

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

thanx

推荐答案

由于每个 TPerson 记录中的两个字符串字段,您可以不要使用二进制move,因为你会混淆 string 的引用计数,特别是在多线程环境中。

Due to the two string fields in each TPerson record, you can't just use binary "move", since you'll mess the reference counting of string - especially in a multi-threaded environment.

您可以手动进行操作 - 这是快速且不错的:

You can do it manually - this is fast and nice:

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 wrapper ,它具有处理这种情况的方法:

Or you can use our TDynArray wrapper, which has a method for handling such cases:

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功能,没有如此优化速度。我写了一个更快的版本 - 请参阅这篇博客文章此论坛主题

Note that with such records, it will use the System._CopyRecord RTL function, which is not so optimized for speed. I've written a faster version - see this blog article or this forum thread.

如果在函数/过程中使用动态数组,不要忘记明确使用 const var 参数(如上面编码的),否则将在每个通话中进行临时复制,因此可能会很慢。

If you use dynamic arrays in functions/procedures, don't forget to use explicitly const or var parameters (as I coded above), otherwise it will make a temporary copy at each call, therefore it may be slow.

这篇关于有没有办法将2个阵列添加到一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆