gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:50:05 33 4
gpt4 key购买 nike

我正在使用 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.

输出

FalseTrueTrueFalse

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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com