在Delphi中调整动态数组大小的最佳方法是什么?

时间:2017-05-29 17:26:54

标签: delphi

作为Delphi新手,我编写了一个简单的函数,它给出了一个字符串和一个字符,返回字符串中字符出现的索引。

但是我不确定我的实现是否是最佳的(因为我不断调整动态数组的大小)。有没有更好的方法来实现这个:

type Indexes = array of Integer;

function GetCharacterIndexesInString(inputstring:string; c:char) : Indexes;
  var
  s : char;
  count : integer;
  position: integer;

  begin
    count := 0;
    position := 0;
    SetLength(result, 0);
    for  s in inputstring do
    begin
      if s = c then
      begin
        count := count+1;
        SetLength(result, count);
        result[count-1] := position;
      end;
      position := position+1;
    end;
  end;

1 个答案:

答案 0 :(得分:6)

当最终大小未知时,有渐近快速数组大小调整的经典算法。每次我们没有空间时,我们不会将其大小调整为1,而是将其大小加倍。完成后,设置数组的实际大小。

以下是代码:

type Indexes = array of Integer;

function GetCharacterIndexesInString(inputstring:string; c:char) : Indexes;
  var
  s : char;
  count : integer;
  position: integer;
  capacity: Integer; //TList uses same method internally :)

  const InitCapacity: Integer = 16;
  begin
    count := 0;
    position := 0;
    capacity := InitCapacity;
    SetLength(result, InitCapacity);
    for  s in inputstring do
    begin
      if s = c then
      begin
        inc(count); //adds 1 to count, delphi analog of ++
        if count > capacity then begin
          capacity := capacity * 2;
          SetLength(result, capacity);
        end;
        result[count-1] := position;
      end;
      inc(position);
    end;
    SetLength(result, count);
  end;

UPD。修改后的代码根据David Heffernan的建议,现在从16的长度开始,这应该加快一点。此外,它可以调整' InitCapacity,代码在这里保持使用任何正数。例如,您可以收集统计信息:结果数组的平均长度,并将InitCapacity设置为略大于此平均长度。

相关问题