任何方式加入2阵列为一体? [英] Is any way to add 2 arrays into one?

查看:104
本文介绍了任何方式加入2阵列为一体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有加2阵列成一个任何简单的方式万向?在它下面的情况下,是不可能简单地使用 C:= A + B 语句...
我想避免algorhytm它每次。

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

感谢名单

推荐答案

由于两个字符串在每个领域 TPerson 的记录,你不能只用二进制的移动,因为你惹字符串的引用计数 - 尤其是在多线程环境。

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;

或者您可以使用我们的<$c$c>TDynArray包装,这对处理这类案件的方法:

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 方法可以增加原数组的一个子端口:

The AddArray method can add a sub-port of the original array:

/// 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.

如果您在使用功能/过程动态数组,不要忘记明确地使用常量 VAR 参数(正如我上面codeD),否则会在每次拨打的临时副本,因此可能会很慢。

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天全站免登陆