D Language
Pętle
Szukaj…
Składnia
- for (<initializer>; <warunek pętli>; <instrukcja pętli>) {<statements>}
- while (<warunek>) {<statements>}
- do {<statements>} while (<warunek>);
- foreach (<el>, <collection>)
- foreach_reverse (<el>, <collection>)
Uwagi
-
for
pętli w Programowanie w D , specyfikacja -
while
pętli w Programowanie w D , specyfikacja -
do while
loop w Programowanie w D , specyfikacja -
foreach
w Programowanie w D , op Zastosuj , specyfikacja
Dla pętli
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
for (int i = 0; i < arr.length; i++)
{
arr[i] *= 2;
}
writeln(arr); // [2, 6, 8]
}
Podczas pętli
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
int i = 0;
while (i < arr.length)
{
arr[i++] *= 2;
}
writeln(arr); // [2, 6, 8]
}
robić
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
int i = 0;
assert(arr.length > 0, "Array must contain at least one element");
do
{
arr[i++] *= 2;
} while (i < arr.length);
writeln(arr); // [2, 6, 8]
}
Dla każdego
Foreach pozwala na mniej podatny na błędy i lepiej czytelny sposób na iterację kolekcji. ref
atrybutu można użyć, jeśli chcemy bezpośrednio zmodyfikować iterowany element.
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (ref el; arr)
{
el *= 2;
}
writeln(arr); // [2, 6, 8]
}
Dostęp do indeksu iteracji można również uzyskać:
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (i, el; arr)
{
arr[i] = el * 2;
}
writeln(arr); // [2, 6, 8]
}
Możliwa jest również iteracja w odwrotnej kolejności:
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
int i = 0;
foreach_reverse (ref el; arr)
{
el += i++; // 4 is incremented by 0, 3 by 1, and 1 by 2
}
writeln(arr); // [3, 4, 4]
}
Przerwa, kontynuacja i etykiety
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4, 5];
foreach (i, el; arr)
{
if (i == 0)
continue; // continue with the next iteration
arr[i] *= 2;
if (i == 2)
break; // stop the loop iteration
}
writeln(arr); // [1, 6, 8, 5]
}
Etykiety mogą być również używane do break
lub continue
w zagnieżdżonych pętlach.
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
outer: foreach (j; 0..10) // iterates with j=0 and j=1
foreach (i, el; arr)
{
arr[i] *= 2;
if (j == 1)
break outer; // stop the loop iteration
}
writeln(arr); // [4, 6, 8] (only 1 reaches the second iteration)
}
Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow