D Language
Loops
Sök…
Syntax
- för (<initierare>; <slingtillstånd>; <slinga uttalande>) {<information>}
- medan (<kondition>) {<information>}
- gör {<information>} medan (<kondition>);
- förhand (<el>, <samling>)
- foreach_reverse (<el>, <collection>)
Anmärkningar
-
for
slinga i programmering i D , specifikation -
while
loop i Programmering i D , specifikation -
do while
slinga i programmering i D , specifikation -
foreach
i programmering i D , opApply , specifikation
Du kan spela med slingor och förhand på nätet.
För slinga
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]
}
Medan slinga
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]
}
göra medan
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]
}
För varje
Foreach tillåter ett mindre felbenägligt och bättre läsbart sätt att iterera samlingar. Attributen ref
kan användas om vi vill ändra det itererade elementet direkt.
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (ref el; arr)
{
el *= 2;
}
writeln(arr); // [2, 6, 8]
}
Indexet för iterationen kan också nås:
void main()
{
import std.stdio : writeln;
int[] arr = [1, 3, 4];
foreach (i, el; arr)
{
arr[i] = el * 2;
}
writeln(arr); // [2, 6, 8]
}
Iteration i omvänd ordning är också möjlig:
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]
}
Bryt, fortsätt & etiketter
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]
}
Etiketter kan också användas för att break
eller continue
inom kapslade öglor.
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
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow