arrays - delphi中如何更改 bool 数组的值

标签 arrays delphi

我正在使用 Delphi XE5 制作一个小型 Delphi 程序。在我的代码中有一个动态 bool 数组,我无法更改某些数组元素的值。我尝试在设置数组的长度后初始化数组,但没有帮助。这是部分代码:

procedure DoSomething(names: array of string);
var startWithA: array of Boolean;
    i: integer;
begin
    SetLength(startWithA, Length(names)); // each element is false by default
    for i := 0 to Length(names) - 1 do begin
       if (names[i].indexOf('A') = 0) then begin
          startWithA[i] := true; // the value is not changed after executing this line
       end;
    end;
end;

最佳答案

你的代码工作得很好。证明如下:

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
  i: Integer;
begin
  SetLength(Result, Length(Names));
  for i := 0 to high(Result) do begin
    if (Names[i].IndexOf('A') = 0) then begin
      Result[i] := true;
    end;
  end;
end;

var
  Indices: TArray<Boolean>;
  b: Boolean;

begin
  Indices := StartsWithAIndices(['Bob', 'Aaron', 'Aardvark', 'Jim']);
  for b in Indices do begin
    Writeln(BoolToStr(b, True));
  end;
  Readln;
end.

输出

False
True
True
False

Perhaps your confusion stems from the fact that you assign to an array that is a local variable and whose values are never read. How can you say that the array values are not modified if you never read from them? Or perhaps you have optimizations enabled and the compiler decided to optimize away the local variable whose values are written to but never read.

As an aside, your function could be written more simply like this:

function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
  i: Integer;
begin
  SetLength(Result, Length(Names));
  for i := 0 to high(Result) do begin
    Result[i] := Names[i].StartsWith('A');
  end;
end;

关于arrays - delphi中如何更改 bool 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23740485/

相关文章:

delphi - 使用 ifileoperation copyitem 时提升 uac

arrays - 插入排序理论分析,总移位数。

arrays - 用其他数组替换部分数组的最简单方法? (将二进制数据修补到文件中)

delphi - Spring4D中是否可以多次注册同一个类/接口(interface)?

德尔福。印地和西里尔字母

android - 为什么我不能在我的设备上调试 Delphi XE7 Android 应用程序?

string - 在Delphi中使用转义序列取消转义字符串

c - 在数组上使用自由函数 (C) 时我的程序崩溃

arrays - cv.Save 和 cv.Load(数组)

java - 空数组返回真?给定一个整数数组,如果每个元素都是 1 或 4,则返回 true