View source code
Display the source code in std/algorithm/iteration.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.

Template std.algorithm.iteration.each

Eagerly iterates over r and calls pred over each element.

template each(alias pred) ;

If no predicate is specified, each will default to doing nothing but consuming the entire range. .front will be evaluated, but this can be avoided by explicitly specifying a predicate lambda with a lazy parameter.

each also supports opApply-based iterators, so it will work with e.g. parallel.

Contained Functions

NameDescription
each

Parameters

NameDescription
pred predicate to apply to each element of the range
r range or iterable over which each iterates

See Also

std.range.tee

Example

import std.range : iota;

long[] arr;
iota(5).each!(n => arr ~= n);
writeln(arr); // [0, 1, 2, 3, 4]

// If the range supports it, the value can be mutated in place
arr.each!((ref n) => n++);
writeln(arr); // [1, 2, 3, 4, 5]

arr.each!"a++";
writeln(arr); // [2, 3, 4, 5, 6]

// by-ref lambdas are not allowed for non-ref ranges
static assert(!is(typeof(arr.map!(n => n).each!((ref n) => n++))));

// The default predicate consumes the range
auto m = arr.map!(n => n);
(&m).each();
assert(m.empty);

// Indexes are also available for in-place mutations
arr[] = 0;
arr.each!"a=i"();
writeln(arr); // [0, 1, 2, 3, 4]

// opApply iterators work as well
static class S
{
    int x;
    int opApply(scope int delegate(ref int _x) dg) { return dg(x); }
}

auto s = new S;
s.each!"a++";
writeln(s.x); // 1

Authors

Andrei Alexandrescu

License

Boost License 1.0.