controls what zip will do if the ranges are different lengths
the ranges to zip together
At minimum, an input range. Zip offers the lowest range facilities of all components, e.g. it offers random access iff all ranges offer random access, and also offers mutation and swapping if all ranges offer it. Due to this, Zip is extremely powerful because it allows manipulating several ranges in lockstep.
An Exception if all of the ranges are not the same length and sp is set to StoppingPolicy.requireSameLength.
Limitations: The @nogc and nothrow attributes cannot be inferred for the Zip struct because StoppingPolicy can vary at runtime. This limitation is not shared by the anonymous range returned by the zip function when not given an explicit StoppingPolicy as an argument.
import std.algorithm.comparison : equal; import std.algorithm.iteration : map; // pairwise sum auto arr = only(0, 1, 2); auto part1 = zip(arr, arr.dropOne).map!"a[0] + a[1]"; assert(part1.equal(only(1, 3)));
import std.conv : to; int[] a = [ 1, 2, 3 ]; string[] b = [ "a", "b", "c" ]; string[] result; foreach (tup; zip(a, b)) { result ~= tup[0].to!string ~ tup[1]; } assert(result == [ "1a", "2b", "3c" ]); size_t idx = 0; // unpacking tuple elements with foreach foreach (e1, e2; zip(a, b)) { assert(e1 == a[idx]); assert(e2 == b[idx]); ++idx; }
zip is powerful - the following code sorts two arrays in parallel:
import std.algorithm.sorting : sort; int[] a = [ 1, 2, 3 ]; string[] b = [ "a", "c", "b" ]; zip(a, b).sort!((t1, t2) => t1[0] > t2[0]); assert(a == [ 3, 2, 1 ]); // b is sorted according to a's sorting assert(b == [ "b", "c", "a" ]);
Iterate several ranges in lockstep. The element type is a proxy tuple that allows accessing the current element in the nth range by using e[n].
zip is similar to lockstep, but lockstep doesn't bundle its elements and uses the opApply protocol. lockstep allows reference access to the elements in foreach iterations.