foreach Loop Properties
This lesson explains the different properties of foreach loop.
We'll cover the following
Counter for containers #
The automatic counter in foreach
is provided only when iterating over arrays. There are two options for other containers:
-
Taking advantage of
std.range.enumerate
-
Defining and incrementing a counter variable explicitly:
size_t i = 0;
foreach (element; container) {
// ...
++i;
}
A counter variable is needed when counting a specific condition as well. For example, the following code only counts the values that are divisible by 10 and displays the count with each occurrence of such an element.
Get hands-on with 1200+ tech skills courses.