RandomAccessRange: Finite
Learn the use of the finite RandomAccessRange.
We'll cover the following
The following are all of the requirements of a RandomAccessRange that is based on a finite BidirectionalRange:
-
empty
,front
andpopFront()
required by InputRange -
save
required by ForwardRange -
back
andpopBack()
required by BidirectionalRange -
opIndex()
required by RandomAccessRange -
length
which provides the length of the range
Example
As an example of a finite RandomAccessRange, let’s define a range that works similar to std.range.chain
. The chain()
function presents the elements of a number of separate ranges as if they are elements of a single larger range. Although chain()
works with any type of element and any type of range, to keep the example short, let’s implement a range that works only with int
slices.
Let’s name this range Together
and expect the following behavior from it:
auto range = Together([ 1, 2, 3 ], [ 101, 102, 103]);
writeln(range[4]);
When constructed with the two separate arrays above, range
should present all of those elements as a single range. For example, although neither array has an element at index 4, the element 102
should be the element that corresponds to index 4 of the collective range:
102
As expected, printing the entire range should contain all of the elements:
writeln(range);
The output:
[1, 2, 3, 101, 102, 103]
Together
will operate lazily. The elements will not be copied to a new larger array; they will be accessed from the original slices.
We can take advantage of variadic functions, which were introduced in the variable number of parameters chapter, to initialize the range by any number of original slices:
Get hands-on with 1400+ tech skills courses.