Function takeExactly
Takes exactly n elements from range.
auto takeExactly(R)
(
R range,
size_t n
)
if (isInputRange!R);
range must have at least n elements.
takeExactly is particulary useful with infinite ranges. You can ` take n elements from such range and pass the result to an algorithm which expects a finit range.
Parameters
Name | Description |
---|---|
R | Type of the adapted range. |
range | The range to take the elements from. |
n | The number of elements to take. |
Returns
A range containing n first elements of range.
See Also
take.
Example
static struct InfiniteRange
{
private size_t front_ = 1;
enum bool empty = false;
@property size_t front() @nogc nothrow pure @safe
{
return this .front_;
}
@property void front(size_t i) @nogc nothrow pure @safe
{
this .front_ = i;
}
void popFront() @nogc nothrow pure @safe
{
++this .front_;
}
size_t opIndex(size_t i) @nogc nothrow pure @safe
{
return this .front_ + i;
}
void opIndexAssign(size_t value, size_t i) @nogc nothrow pure @safe
{
this .front = i + value;
}
InfiniteRange save() @nogc nothrow pure @safe
{
return this;
}
}
auto t = InfiniteRange() .takeExactly(3);
assert(t .length == 3);
assert(t .front == 1);
assert(t .back == 3);
t .popFront();
assert(t .front == 2);
assert(t .back == 3);
t .popBack();
assert(t .front == 2);
assert(t .back == 2);
t .popFront();
assert(t .empty);