将数组分成 3 个单独的数组

dividing an array into 3 individual arrays

我有 45 个值存储在一个数组中,sample。它需要分成三个大小为 15 的单独数组,sample1sample2sample3:前 15 项分为 sample1,接下来的 15 项分为 sample2,剩下的15个变成sample3。我试着用这段代码来做到这一点:

var
  sample: array of integer; // Source Array which contains data
  sample1, sample2, sample3: array of integer; //Target arrays which needs to be worked upon
  i: integer;
begin
 SetLength(sample1, 15);
 SetLength(sample2, 15);
 SetLength(sample3, 15); 
 for i := 0 to 14 do
   sample[i] := sample1[i];
 for i:= 15 to 29 do
   sample[i] := sample2[i];  
 for i:= 30 to 44 do
   sample[i] := sample3[i];
 i := i + 1;

我可以在第一个数组中得到结果,但不能在其他数组中得到结果。我做错了什么?

如果我理解你的话,下面就是你想要的。我假设你的 sample 数组恰好有 45 个项目,所以你可能想这样做:

var 
  sample: array of Integer;
  sample1, sample2, sample3: array of Integer;
  i: Integer;
begin
  SetLength(sample, 45);
  { fill sample with values }
  ...
  { now split: }
  SetLength(sample1, 15);
  SetLength(sample2, 15);
  SetLength(sample3, 15);
  for i := 0 to 14 do
  begin
    sample1[i] := sample[i];
    sample2[i] := sample[i + 15]; { i = 0..14, so i+15 = 15..29 }
    sample3[i] := sample[i + 30]; { i = 0..14, so i+30 = 30..44 } 
  end;

这应该可以解决问题。如果这不是您想要的,那么您应该更好地说明您的问题。如果您 sample 数组更长,则不会拆分所有数组。如果您的 sample 数组较短,则会发生溢出,从而导致错误或未定义的行为。

您正在将目标数组分配给源数组,而不是相反。无论如何你都在使用错误的索引。

尝试更像这样的东西:

var
  sample: array of integer;
  sample1, sample2, sample3: array of integer;
  i: integer;
begin
  ...
  SetLength(sample1, 15);
  SetLength(sample2, 15);
  SetLength(sample3, 15); 
  for i := 0 to 14 do
    sample1[i] := sample[i];
  for i := 0 to 14 do
    sample2[i] := sample[15+i];  
  for i := 0 to 14 do
    sample3[i] := sample[30+i];
  ...

或者:

var
  sample: array of integer;
  sample1, sample2, sample3: array of integer;
  i: integer;
begin
  ...
  SetLength(sample1, 15);
  SetLength(sample2, 15);
  SetLength(sample3, 15); 
  for i := 0 to 14 do
  begin
    sample1[i] := sample[i];
    sample2[i] := sample[15+i];  
    sample3[i] := sample[30+i];
  end;
  ...

因为你的目标数组无论如何都是动态的,我建议使用 Copy() 而不是任何手动循环:

var
  sample, sample1, sample2, sample3: array of integer;
begin
 ...
 sample1 := Copy(sample, 0, 15);
 sample2 := Copy(sample, 15, 15);
 sample3 := Copy(sample, 30, 15);