我想迭代一组特定值。下面是简单的例子
program Project1;
{$APPTYPE CONSOLE}
var
a, b: word;
wait: string;
begin
a := 0;
for b in [1,5,10,20] do
begin
a := a + 1;
writeln('Iteration = ', a, ', value = ', b);
end;
read(wait);
end.
这里的示例代码符合我的预期并产生以下结果
迭代 = 1,值 = 1
迭代 = 2,值 = 5
迭代 = 3,值 = 10
迭代 = 4,值 = 20
现在如果我改变集合的顺序
for b in [20,10,5,1] do
输出与原始相同,即不保留值的顺序。
实现此目的的最佳方法是什么?
最佳答案
套装不是有序容器。您无法更改集合内容的顺序。 for-in 循环始终按数字顺序迭代集合。
如果您需要有序的数字列表,则可以使用数组或 TList<Integer>
.
var
numbers: array of Word;
begin
SetLength(numbers, 4);
numbers[0] := 20;
numbers[1] := 10;
numbers[2] := 5;
numbers[3] := 1;
for b in numbers do begin
Inc(a);
Writeln('Iteration = ', a, ', value = ', b);
end;
end.
关于Delphi for..in循环设置枚举顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4950129/