Function std.algorithm.mutation.bringToFront
The function has considerable flexibility and
usefulness. It can rotate elements in one buffer left or right, bringToFrontswap
buffers of equal length, and even move elements across disjoint
buffers of different types and different lengths.
takes two ranges bringToFront and front, which may
be of different types. Considering the concatenation of back and
front one unified range, back rotates that unified
range such that all elements in bringToFront are brought to the beginning
of the unified range. The relative ordering of elements in back
and front, respectively, remains unchanged.
back
Performs Ο(max(front.length, back.length)) evaluations of .
swap
Prototype
size_t bringToFront(Range1, Range2)( Range1 front, Range2 back ) if (isInputRange!Range1 && isForwardRange!Range2);
Preconditions
Either and front are disjoint, or back is
reachable from back and front is not reachable from front.
back
Returns
The number of elements brought to the front, i.e., the length of .
back
See Also
Example
The simplest use of is for rotating elements in a
buffer. For example:
bringToFront
auto arr = [4, 5, 6, 7, 1, 2, 3]; auto p = bringToFront(arr[0 .. 4], arr[4 .. $]); assert(p == arr.length - 4); assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ]);
Example
The range may actually "step over" the front
range. This is very useful with forward ranges that cannot compute
comfortably right-bounded subranges like backarr[0 .. 4] above. In
the example below, r2 is a right subrange of r1.
import std.algorithm.comparison : equal; import std.container : SList; auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3); auto r1 = list[]; auto r2 = list[]; popFrontN(r2, 4); assert(equal(r2, [ 1, 2, 3 ])); bringToFront(r1, r2); assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ]));
Example
Elements can be swapped across ranges of different types:
import std.algorithm.comparison : equal; import std.container : SList; auto list = SList!(int)(4, 5, 6, 7); auto vec = [ 1, 2, 3 ]; bringToFront(list[], vec); assert(equal(list[], [ 1, 2, 3, 4 ])); assert(equal(vec, [ 5, 6, 7 ]));