enumerate

Iterate over range with an attached index variable.

Each element is a std.typecons.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.length is bigger than Enumerator.max, thus it is ensured that overflow cannot happen.

If range does not have length, and popFront is called when front.index == Enumerator.max, the index will overflow and continue from Enumerator.min.

enumerate
(
Enumerator = size_t
Range
)
(
Range range
,
Enumerator start = 0
)
if (
isIntegral!Enumerator &&
isInputRange!Range
)

Parameters

range Range

the input range to attach indexes to

start Enumerator

the number to start the index counter from

Return Value

Type: auto

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.

Examples

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);

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]);

Meta