View source code Display the source code in std/range.d from which this page was generated on github. 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. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.range.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.

Bidirectionality is propagated only if range has length.

Prototype

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

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.

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

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, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.

License

Boost License 1.0.

Comments