Function std.range.enumerate
Iterate over range with an attached index variable.
auto enumerate(Enumerator, Range)
(
Range range,
Enumerator start = 0
)
if (isIntegral!Enumerator && isInputRange!Range);
Each element is a Tuple containing the index
and the element, in that order, where the index member is named index
and the element member is named value.
The index starts at start and is incremented by one on every iteration.
Overflow
If range has length, then it is an error to pass a value for start
so that start + range is bigger than Enumerator, thus
it is ensured that overflow cannot happen.
If range does not have length, and popFront is called when
front, the index will overflow and
continue from Enumerator.
Parameters
| Name | Description |
|---|---|
| range | the input range to attach indexes to |
| start | the number to start the index counter from |
Returns
At minimum, an input range. All other range primitives are given in the
resulting range if range has them. The exceptions are the bidirectional
primitives, which are propagated only if range has length.
Example
Useful for using foreach with an index loop variable:
import std .stdio : stdin, stdout;
import std .range : enumerate;
foreach (lineNum, line; stdin .byLine() .enumerate(1))
stdout .writefln("line #%s: %s", lineNum, line);
Example
Can start enumeration from a negative position:
import std .array : assocArray;
import std .range : enumerate;
bool[int] aa = true .repeat(3) .enumerate(-1) .assocArray();
assert(aa[-1]);
assert(aa[0]);
assert(aa[1]);
Authors
Andrei Alexandrescu, David Simcha, Jonathan M Davis, and Jack Stouffer. Credit for some of the ideas in building this module goes to Leonardo Maffi.