简体   繁体   English

填充二维数组的最佳方法是什么?

[英]What is the best way to fill a 2D array?

I am trying to fill an array using data from a database (Access), but when I run this code:我正在尝试使用数据库(Access)中的数据填充数组,但是当我运行此代码时:

with dmSUPREMEDATA do
begin
  iNumberofRecords := ADOComplete.RecordCount;
  ADOComplete.First;
  SetLength(ArrSummary, iNumberofRecords, 3);
  for i := 0 to iNumberofRecords do
  begin
    ArrSummary[i, 0] := ADOComplete['Names'];
    ArrSummary[i, 1] := ADOComplete['Surnames'];
    ArrSummary[i, 2] := ADOComplete['Average'];
    ADOComplete.Next;
  end;
end;

This is the error that pops up:这是弹出的错误:

图片

Is there a better way to fill the array?有没有更好的方法来填充数组? This is coded with delphi这是用 delphi 编码的

Your loop is going out out bounds of the array.您的循环超出了数组的范围。

The 1st dimension of the array has iNumberofRecords number of elements, so it has valid indexes 0..iNumberofRecords-1 .数组的第一维具有iNumberofRecords个元素,因此它具有有效索引0..iNumberofRecords-1 The indexes that a for loop uses are inclusive , so you are looping through indexes 0..iNumberofRecords , which means the final iteration of the loop is accessing an invalid index. for循环使用的索引是inclusive ,因此您正在遍历索引0..iNumberofRecords ,这意味着循环的最终迭代正在访问无效索引。

You need to subtract -1 from the loop counter, eg:您需要从循环计数器中减去-1 ,例如:

for i := 0 to iNumberofRecords-1 do

or:或者:

for i := 0 to Pred(iNumberofRecords) do

You can try create two for loops.您可以尝试创建两个 for 循环。 Like a detail and subdetail, being one for the first array and other for the second.就像细节和子细节一样,一个用于第一个数组,另一个用于第二个。


var arr2d := array of array of string;

SetLength(arr2d, 5, 5);

for var i := 0 to Length(arr2d) - 1 do
begin
  for var j := 0 to Length(arr2d) - 1 do
    arr2d[i][j] := 'Text [' + i.ToString + '][' + j.toString + ']';
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM