我有45个值存储在数组sample
中。它需要分成三个大小为15的单个数组,sample1
,sample2
和sample3
:前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;
我能够在第一个数组中获得结果,但不能在其他数组中获得结果。我做错了什么?
答案 0 :(得分:3)
您正在将目标数组分配给源数组,而不是相反。无论如何,你使用了错误的索引。
尝试更像这样的东西:
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);
答案 1 :(得分: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
数组较短,则会出现溢出,导致错误或未定义的行为。