View source code
Display the source code in std/range/package.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.range.enumerate

Iterate over range with an attached index variable.

auto 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.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.

Parameters

NameDescription
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.

License

Boost License 1.0.