gpt4 book ai didi

arrays - 计算数组中有多少个元素

转载 作者:行者123 更新时间:2023-12-03 18:13:03 26 4
gpt4 key购买 nike

有没有办法通过使用代码来计算数组中有多少元素?

例如:

arrName   : array[1..20] of string;

我已经知道该数组中存储了 6 个名称,但是如何使用编码来确定呢?

最佳答案

是的,但前提是数组包含托管类型。
看看下面的代码示例。

procedure TForm1.Button1Click(Sender: TObject);
var
sa: array[0..19] of string;
i: Integer;
begin
for i := 0 to 5 do
sa[i]:= 'test'+IntToStr(i);
for i := 6 to High(sa) do begin
if sa[i] <> '' then ShowMessage('oops'); //will never be triggered.
end;
end;

注意空字符串又名 ''是一个有效的字符串。如果您允许程序在此数组中存储空字符串,您的方案将失败;如果是这样,您需要使用占位符字符串初始化数组。

托管类型初始化为空
当您调试此示例并调出 CPU 窗口时,您将看到以下初始化代码:
Unit1.pas.30: begin
005C9B24 55 push ebp
005C9B25 8BEC mov ebp,esp
......
005C9B3F E8F811E4FF call @InitializeArray
......
Unit1.pas.31: for i := 0 to 5 do

begin声明调用 InitializeArray因为数组包含 string .

If the array contains: string , interface , dynamic array , variant or anonymous method (or records containing any of these) then it will be initialized.

非托管类型未初始化
如果数组包含其他任何内容,它将不会被初始化;这意味着它将包含之前那段内存中的任何内容。
procedure TForm1.Button1Click(Sender: TObject);
var
sa: array[0..19] of integer;
i: Integer;
begin
for i := 0 to 5 do
sa[i]:= i+1;
for i := 6 to High(sa) do begin
//will most likely be triggered
if sa[i] <> 0 then ShowMessage('no init for integer');
end;
end;

(显然 **dynamic** array(一个没有预设边界的数组)在使用前和扩展时将被归零)

这不适用于类(class)成员
当创建对象(该类的实例)时,类的所有成员(又名字​​段)都被初始化为零。
Global variables are also zero initialized.方法的局部变量不是。

聪明的编程
如果你被迫使用一个固定长度的数组来存储可变数量的字符串,那么通过遍历数组来计算项目的数量是很浪费的。
最好有一个计数器来跟踪元素的数量。
type
TNames = record
count: integer;
items: array[0..20] of string;
end;

否则你会陷入 Schlemiel the painter陷阱;一个众所周知的反模式。

关于arrays - 计算数组中有多少个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39937717/

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