将一个元素附加到动态数组 [英] Appending one element to a dynamic array

查看:68
本文介绍了将一个元素附加到动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码中非常常见的模式:

This is a very frequent pattern throughout my code:

SetLength(SomeDynamicArray, Length(SomeDynamicArray)+1);
SomeDynamicArray[High(SomeDynamicArray)] := NewElement;

没有办法在一行中做到这一点吗?

Is there no way to do this in one line?

编辑:这是非常低效的。我知道。我最先使用动态数组(在我自己的代码中,在我自己的个人项目中),因为它们是最容易使用的,而且我只需要用尽可能少的代码就可以完成工作。

This is incredibly inefficient. I know. I use dynamic arrays (in my own code, in my personal projects which only I use) foremost because they are the easiest to use, and I just need to get things done with as little code as possible.

推荐答案

这里有一个泛型黑客,仅适用于 TArray< T>

Here's a hack with generics which only works with TArray<T>:

type
  TAppender<T> = class
    class procedure Append(var Arr: TArray<T>; Value: T);
  end;

class procedure TAppender<T>.Append;
begin
  SetLength(Arr, Length(Arr)+1);
  Arr[High(Arr)] := Value;
end;

用法:

var
  TestArray: TArray<Integer>;

begin
  TAppender<Integer>.Append(TestArray, 5);
end.

这篇关于将一个元素附加到动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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