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.

std.range.zip - multiple declarations

Function zip

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 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. For example, the following code sorts two arrays in parallel:

Prototypes

auto zip(Ranges...)(
  Ranges ranges
)
if (Ranges.length && allSatisfy!(isInputRange, Ranges));

auto zip(Ranges...)(
  StoppingPolicy sp,
  Ranges ranges
)
if (Ranges.length && allSatisfy!(isInputRange, Ranges));

Example

import std.algorithm : sort;
int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "b", "c" ];
sort!((c, d) => c[0] > d[0])(zip(a, b));
assert(a == [ 3, 2, 1 ]);
assert(b == [ "c", "b", "a" ]);

Example

int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "b", "c" ];

size_t idx = 0;
foreach (e; zip(a, b))
{
    assert(e[0] == a[idx]);
    assert(e[1] == b[idx]);
    ++idx;
}

Struct Zip

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 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. For example, the following code sorts two arrays in parallel:

Constructors

Name Description
this Builds an object. Usually this is invoked indirectly by using the zip function.

Properties

Name Type Description
front [get] ElementType Returns the current iterated element.

Methods

Name Description
popFront Advances to the next element in all controlled ranges.

Example

import std.algorithm : sort;
int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "b", "c" ];
sort!((c, d) => c[0] > d[0])(zip(a, b));
assert(a == [ 3, 2, 1 ]);
assert(b == [ "c", "b", "a" ]);

Example

int[] a = [ 1, 2, 3 ];
string[] b = [ "a", "b", "c" ];

size_t idx = 0;
foreach (e; zip(a, b))
{
    assert(e[0] == a[idx]);
    assert(e[1] == b[idx]);
    ++idx;
}

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