Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.111.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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 usinga local clone.

std.algorithm.searching

This is a submodule ofstd.algorithm.It contains generic searching algorithms.
Cheat Sheet
Function NameDescription
allall!"a > 0"([1, 2, 3, 4]) returnstrue because all elements are positive
anyany!"a > 0"([1, 2, -3, -4]) returnstrue because at least one element is positive
balancedParensbalancedParens("((1 + 1) / 2)", '(', ')') returnstrue because the string has balanced parentheses.
boyerMooreFinderfind("hello world", boyerMooreFinder("or")) returns"orld" using the Boyer-Moore algorithm.
canFindcanFind("hello world", "or") returnstrue.
count Counts all elements or elements matching a predicate, specific element or sub-range.
count([1, 2, 1]) returns3,count([1, 2, 1], 1) returns2 andcount!"a < 0"([1, -3, 0]) returns1.
countUntilcountUntil(a, b) returns the number of steps taken ina to reachb; for example,countUntil("hello!", "o") returns4.
commonPrefixcommonPrefix("parakeet", "parachute") returns"para".
endsWithendsWith("rocks", "ks") returnstrue.
extremaextrema([2, 1, 3, 5, 4]) returns[1, 5].
findfind("hello world", "or") returns"orld" using linear search. (For binary search refer tostd.range.SortedRange.)
findAdjacentfindAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e.[3, 3, 4].
findAmongfindAmong("abcd", "qcx") returns"cd" because'c' is among"qcx".
findSkip Ifa = "abcde", thenfindSkip(a, "x") returnsfalse and leavesa unchanged, whereasfindSkip(a, "c") advancesa to"de" and returnstrue.
findSplitfindSplit("abcdefg", "de") returns a tuple of three ranges"abc","de", and"fg".
findSplitAfterfindSplitAfter("abcdefg", "de") returns a tuple of two ranges"abcde" and"fg".
findSplitBeforefindSplitBefore("abcdefg", "de") returns a tuple of two ranges"abc" and"defg".
minCountminCount([2, 1, 1, 4, 1]) returnstuple(1, 3).
maxCountmaxCount([2, 4, 1, 4, 1]) returnstuple(4, 2).
minElement Selects the minimal element of a range.minElement([3, 4, 1, 2]) returns1.
maxElement Selects the maximal element of a range.maxElement([3, 4, 1, 2]) returns4.
minIndex Index of the minimal element of a range.minIndex([3, 4, 1, 2]) returns2.
maxIndex Index of the maximal element of a range.maxIndex([3, 4, 1, 2]) returns1.
minPosminPos([2, 3, 1, 3, 4, 1]) returns the subrange[1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element.
maxPosmaxPos([2, 3, 1, 3, 4, 1]) returns the subrange[4, 1], i.e., positions the range at the first occurrence of its maximal element.
skipOver Assumea = "blah". ThenskipOver(a, "bi") leavesa unchanged and returnsfalse, whereasskipOver(a, "bl") advancesa to refer to"ah" and returnstrue.
startsWithstartsWith("hello, world", "hello") returnstrue.
until Lazily iterates a range until a specific value is found.
License:
Boost License 1.0.
Authors:
Andrei Alexandrescu

Sourcestd/algorithm/searching.d

templateall(alias pred = "a")
Checks ifall of the elements satisfypred.
Examples:
assert(all!"a & 1"([1, 3, 5, 7, 9]));assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));
Examples:
all can also be used without a predicate, if its items can beevaluated to true or false in a conditional statement. This can be aconvenient way to quickly evaluate thatall of the elements of a rangeare true.
int[3] vals = [5, 3, 18];assert(all(vals[]));
boolall(Range)(Rangerange)
if (isInputRange!Range && (__traits(isTemplate, pred) || is(typeof(unaryFun!pred(range.front)))));
Returnstrue if and only if the input rangerange is empty orall values found inrange satisfy the predicatepred. Performs (at most)Ο(range.length) evaluations ofpred.
templateany(alias pred = "a")
Checks ifany of the elements satisfiespred.!any can be used to verify thatnone of the elements satisfypred.This is sometimes calledexists in other languages.
Examples:
import std.ascii : isWhite;assert( all!(any!isWhite)(["a a","b b"]));assert(!any!(all!isWhite)(["a a","b b"]));
Examples:
any can also be used without a predicate, if its items can beevaluated to true or false in a conditional statement.!any can be aconvenient way to quickly test thatnone of the elements of a rangeevaluate to true.
int[3] vals1 = [0, 0, 0];assert(!any(vals1[]));//none of vals1 evaluate to trueint[3] vals2 = [2, 0, 2];assert(any(vals2[]));assert(!all(vals2[]));int[3] vals3 = [3, 3, 3];assert(any(vals3[]));assert( all(vals3[]));
boolany(Range)(Rangerange)
if (isInputRange!Range && (__traits(isTemplate, pred) || is(typeof(unaryFun!pred(range.front)))));
Returnstrue if and only if the input rangerange is non-empty andany value found inrange satisfies the predicatepred. Performs (at most)Ο(range.length) evaluations ofpred.
boolbalancedParens(Range, E)(Ranger, ElPar, ErPar, size_tmaxNestingLevel = size_t.max)
if (isInputRange!Range && is(typeof(r.front ==lPar)));
Checks whetherr has "balanced parentheses", i.e. all instancesoflPar are closed by corresponding instances ofrPar. TheparametermaxNestingLevel controls the nesting level allowed. Themost common uses are the default or0. In the latter case, nonesting is allowed.
Parameters:
RangerThe range to check.
ElParThe element corresponding with a left (opening) parenthesis.
ErParThe element corresponding with a right (closing) parenthesis.
size_tmaxNestingLevelThe maximum allowed nesting level.
Returns:
true if the given range has balanced parenthesis within the given maximum nesting level; false otherwise.
Examples:
auto s ="1 + (2 * (3 + 1 / 2)";assert(!balancedParens(s, '(', ')'));s ="1 + (2 * (3 + 1) / 2)";assert(balancedParens(s, '(', ')'));s ="1 + (2 * (3 + 1) / 2)";assert(!balancedParens(s, '(', ')', 0));s ="1 + (2 * 3 + 1) / (2 - 5)";assert(balancedParens(s, '(', ')', 0));s ="f(x) = ⌈x⌉";assert(balancedParens(s, '⌈', '⌉'));
structBoyerMooreFinder(alias pred, Range);

BoyerMooreFinder!(binaryFun!pred, Range)boyerMooreFinder(alias pred = "a == b", Range)(Rangeneedle)
if (isRandomAccessRange!Range && hasSlicing!Range || isSomeString!Range);
Sets up Boyer-Moore matching for use withfind below. By default, elements are compared for equality.
BoyerMooreFinder allocates GC memory.
Parameters:
predPredicate used to compare elements.
RangeneedleA random-access range with length and slicing.
Returns:
An instance ofBoyerMooreFinder that can be used withfind() to invoke the Boyer-Moore matching algorithm for finding ofneedle in a given haystack.
Examples:
auto bmFinder =boyerMooreFinder("TG");string r ="TAGTGCCTGA";// search for the first match in the haystack rr = bmFinder.beFound(r);writeln(r);// "TGCCTGA"// continue search in haystackr = bmFinder.beFound(r[2 .. $]);writeln(r);// "TGA"
this(Rangeneedle);
RangebeFound(Rangehaystack) scope;
@property size_tlength();
aliasopDollar = length;
autocommonPrefix(alias pred = "a == b", R1, R2)(R1r1, R2r2)
if (isForwardRange!R1 && isInputRange!R2 && !isNarrowString!R1 && is(typeof(binaryFun!pred(r1.front,r2.front))));

autocommonPrefix(alias pred, R1, R2)(R1r1, R2r2)
if (isNarrowString!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(r1.front,r2.front))));

autocommonPrefix(R1, R2)(R1r1, R2r2)
if (isNarrowString!R1 && isInputRange!R2 && !isNarrowString!R2 && is(typeof(r1.front ==r2.front)));

autocommonPrefix(R1, R2)(R1r1, R2r2)
if (isNarrowString!R1 && isNarrowString!R2);
Returns the common prefix of two ranges.
Parameters:
predThe predicate to use in comparing elements for commonality. Defaults to equality"a == b".
R1r1Aforward range of elements.
R2r2Aninput range of elements.
Returns:
A slice ofr1 which contains the characters that both ranges start with,if the first argument is a string; otherwise, the same as the result oftakeExactly(r1, n), wheren is the number of elements in the commonprefix of both ranges.
See Also:
Examples:
writeln(commonPrefix("hello, world","hello, there"));// "hello, "
size_tcount(alias pred = "a == b", Range, E)(Rangehaystack, Eneedle)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(haystack.front,needle))));

size_tcount(alias pred = "a == b", R1, R2)(R1haystack, R2needle)
if (isForwardRange!R1 && !isInfinite!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front,needle.front))));
Counts matches ofneedle inhaystack.
The first overload counts each elemente inhaystack forwhichpred(e,needle) istrue.pred defaults toequality. PerformsΟ(haystack.length) evaluations ofpred.
The second overload counts the number of timesneedle was matched inhaystack.pred compares elements in each range.Throws an exception ifneedle.empty istrue, as the countof the empty range in any range would be infinite. Overlapped countsarenot considered, for examplecount("aaa", "aa") is1, not2.

NoteRegardless of the overload,count will not acceptinfinite ranges forhaystack.

Parameters:
predThe predicate to compare elements.
RangehaystackThe range to count.
EneedleThe element or sub-range to count inhaystack.
Returns:
The number of matches inhaystack.
Examples:
// count elements in rangeint[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];writeln(count(a, 2));// 3writeln(count!("a > b")(a, 2));// 5
Examples:
import std.uni : toLower;// count range in rangewriteln(count("abcadfabf","ab"));// 2writeln(count("ababab","abab"));// 1writeln(count("ababab","abx"));// 0// fuzzy count range in rangewriteln(count!((a, b) => toLower(a) == toLower(b))("AbcAdFaBf","ab"));// 2
size_tcount(alias pred, R)(Rhaystack)
if (isInputRange!R && !isInfinite!R && is(typeof(unaryFun!pred(haystack.front))));

size_tcount(R)(Rhaystack)
if (isInputRange!R && !isInfinite!R);
Counts all elements or elements satisfying a predicate inhaystack.
The first overload counts each elemente inhaystack for whichpred(e) istrue. PerformsΟ(haystack.length) evaluations ofpred.
The second overload counts the number of elements in a range.If the given range has thelength property,that is returned right away, otherwiseperformsΟ(haystack.length) to walk the range.
Parameters:
predOptional predicate to find elements.
RhaystackThe range to count.
Returns:
The number of elements inhaystack (for whichpred returned true).
Examples:
// count elements in rangeint[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];writeln(count(a));// 9// count predicate in rangewriteln(count!("a > 2")(a));// 5
autocountUntil(alias pred = "a == b", R, Rs...)(Rhaystack, Rsneedles)
if (isForwardRange!R && (Rs.length > 0) && (isForwardRange!(Rs[0]) == isInputRange!(Rs[0])) && allSatisfy!(canTestStartsWith!(pred, R), Rs));

ptrdiff_tcountUntil(alias pred = "a == b", R, N)(Rhaystack, Nneedle)
if (isInputRange!R && is(typeof(binaryFun!pred(haystack.front,needle)) : bool));

ptrdiff_tcountUntil(alias pred, R)(Rhaystack)
if (isInputRange!R && is(typeof(unaryFun!pred(haystack.front)) : bool));
Counts elements in the givenforward range until the given predicate is true for one of the givenneedles.
Parameters:
predThe predicate for determining when to stop counting.
RhaystackTheinput range to be counted.
RsneedlesEither a single element, or aforward range of elements, to be evaluated in turn against each element inhaystack under the given predicate.
Returns:
The number of elements which must be popped from the front ofhaystack before reaching an element for whichstartsWith!pred(haystack,needles) istrue. IfstartsWith!pred(haystack,needles) is nottrue for any element inhaystack, then-1 is returned. If more than one needle is provided,countUntil will wrap the result in a tuple similar toTuple!(ptrdiff_t, "steps", ptrdiff_tneedle)
See Also:
Examples:
writeln(countUntil("hello world","world"));// 6writeln(countUntil("hello world", 'r'));// 8writeln(countUntil("hello world","programming"));// -1writeln(countUntil("日本語","本語"));// 1writeln(countUntil("日本語", '語'));// 2writeln(countUntil("日本語","五"));// -1writeln(countUntil("日本語", '五'));// -1writeln(countUntil([0, 7, 12, 22, 9], [12, 22]));// 2writeln(countUntil([0, 7, 12, 22, 9], 9));// 4writeln(countUntil!"a > b"([0, 7, 12, 22, 9], 20));// 3// supports multiple needlesauto res ="...hello".countUntil("ha","he");writeln(res.steps);// 3writeln(res.needle);// 1// returns -1 if no needle was foundres ="hello".countUntil("ha","hu");writeln(res.steps);// -1writeln(res.needle);// -1
Examples:
import std.ascii : isDigit;import std.uni : isWhite;writeln(countUntil!(isWhite)("hello world"));// 5writeln(countUntil!(isDigit)("hello world"));// -1writeln(countUntil!"a > 20"([0, 7, 12, 22, 9]));// 3
uintendsWith(alias pred = "a == b", Range, Needles...)(RangedoesThisEnd, NeedleswithOneOfThese)
if (isBidirectionalRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles));

boolendsWith(alias pred = "a == b", R1, R2)(R1doesThisEnd, R2withThis)
if (isBidirectionalRange!R1 && isBidirectionalRange!R2 && is(typeof(binaryFun!pred(doesThisEnd.back,withThis.back)) : bool));

boolendsWith(alias pred = "a == b", R, E)(RdoesThisEnd, EwithThis)
if (isBidirectionalRange!R && is(typeof(binaryFun!pred(doesThisEnd.back,withThis)) : bool));

boolendsWith(alias pred, R)(RdoesThisEnd)
if (isInputRange!R && ifTestable!(typeof(doesThisEnd.front), unaryFun!pred));
Checks if the given range ends with (one of) the given needle(s).The reciprocal ofstartsWith.
Parameters:
predThe predicate to use for comparing elements between the range and the needle(s).
RangedoesThisEndThebidirectional range to check.
NeedleswithOneOfTheseThe needles to check against, which may be single elements, or bidirectional ranges of elements.
R2withThisThe single element to check.
Returns:
0 if the needle(s) do not occur at the end of the given range;otherwise the position of the matching needle, that is, 1 if the range endswithwithOneOfThese[0], 2 if it ends withwithOneOfThese[1], and soon.
In the case when no needle parameters are given, returntrue iff back ofdoesThisStart fulfils predicatepred.
Examples:
import std.ascii : isAlpha;assert("abc".endsWith!(a => a.isAlpha));assert("abc".endsWith!isAlpha);assert(!"ab1".endsWith!(a => a.isAlpha));assert(!"ab1".endsWith!isAlpha);assert(!"".endsWith!(a => a.isAlpha));import std.algorithm.comparison : among;assert("abc".endsWith!(a => a.among('c', 'd') != 0));assert(!"abc".endsWith!(a => a.among('a', 'b') != 0));assert(endsWith("abc",""));assert(!endsWith("abc","b"));writeln(endsWith("abc","a", 'c'));// 2writeln(endsWith("abc","c","a"));// 1writeln(endsWith("abc","c","c"));// 1writeln(endsWith("abc","bc","c"));// 2writeln(endsWith("abc","x","c","b"));// 2writeln(endsWith("abc","x","aa","bc"));// 3writeln(endsWith("abc","x","aaa","sab"));// 0writeln(endsWith("abc","x","aaa", 'c',"sab"));// 3
InputRangefind(alias pred, InputRange)(InputRangehaystack)
if (isInputRange!InputRange);
Finds an elemente of aninput rangewherepred(e) istrue.

  • find behaves similarly todropWhile in other languages.
  • To find thelast matching element in abidirectionalhaystack,callfind!pred(retro(haystack)). Seestd.range.retro.

Complexityfind performsΟ(walkLength(haystack)) evaluations ofpred.

Parameters:
predThe predicate to match an element.
InputRangehaystackTheinput range searched in.
Returns:
haystack advanced such that the front element satisfiespred. If no such element exists, returns an emptyhaystack.
Examples:
auto arr = [ 1, 2, 3, 4, 1 ];writeln(find!("a > 2")(arr));// [3, 4, 1]// with predicate aliasbool pred(int e) => e + 1 > 1.5;writeln(find!(pred)(arr));// arr
InputRangefind(alias pred = "a == b", InputRange, Element)(InputRangehaystack, scope Elementneedle)
if (isInputRange!InputRange && is(typeof(binaryFun!pred(haystack.front,needle)) : bool) && !is(typeof(binaryFun!pred(haystack.front,needle.front)) : bool));

R1find(alias pred = "a == b", R1, R2)(R1haystack, scope R2needle)
if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front,needle.front)) : bool));
Finds an individual element in aninput range.Elements ofhaystack are compared withneedle by using predicatepred withpred(haystack.front,needle).The predicate is passed tostd.functional.binaryFun, and can either accept astring, or any callable that can be executed viapred(element, element).
Ifhaystack is aforward range,needle can be aforward range too.In this casestartsWith!pred(haystack,needle) is evaluated on each evaluation.
Note: To find the first elementnot matching the needle, use predicate"a != b".

Complexityfind performsΟ(walkLength(haystack)) evaluations ofpred. There are specializations that improve performance by taking advantage ofbidirectional orrandom access ranges (where possible).

Parameters:
predThe predicate for comparing each element with the needle, defaulting to equality"a == b".
InputRangehaystackTheinput range searched in.
ElementneedleThe element searched for.
Returns:
haystack advanced such that the front element is the one searched for; that is, untilbinaryFun!pred(haystack.front,needle) istrue. If no such position exists, returns an emptyhaystack.
See Also:
Examples:
import std.range.primitives;auto arr = [1, 2, 4, 4, 4, 4, 5, 6, 9];writeln(arr.find(4));// [4, 4, 4, 4, 5, 6, 9]writeln(arr.find(1));// arrwriteln(arr.find(9));// [9]writeln(arr.find!((e, n) => e > n)(4));// [5, 6, 9]writeln(arr.find!((e, n) => e < n)(4));// arrassert(arr.find(0).empty);assert(arr.find(10).empty);assert(arr.find(8).empty);writeln(find("hello, world", ','));// ", world"
Examples:
Case-insensitive find of a string
import std.range.primitives;import std.uni : toLower;string[] s = ["Hello","world","!"];writeln(s.find!((e, n) => toLower(e) == n)("hello"));// s
Examples:
import std.container : SList;import std.range.primitives : empty;import std.typecons : Tuple;assert(find("hello, world","World").empty);writeln(find("hello, world","wo"));// "world"writeln([1, 2, 3, 4].find(SList!int(2, 3)[]));// [2, 3, 4]alias C = Tuple!(int,"x",int,"y");auto a = [C(1,0), C(2,0), C(3,1), C(4,0)];writeln(a.find!"a.x == b"([2, 3]));// [C(2, 0), C(3, 1), C(4, 0)]writeln(a[1 .. $].find!"a.x == b"([2, 3]));// [C(2, 0), C(3, 1), C(4, 0)]
Tuple!(Range, size_t)find(alias pred = "a == b", Range, Needles...)(Rangehaystack, Needlesneedles)
if (Needles.length > 1 && is(typeof(startsWith!pred(haystack,needles))));
Finds two or moreneedles into ahaystack. The predicatepred is used throughout to compare elements. By default, elements arecompared for equality.
Parameters:
predThe predicate to use for comparing elements.
RangehaystackThe target of the search. Must be an input range.If any ofneedles is a range with elements comparable toelements inhaystack, thenhaystack must be aforward rangesuch that the search can backtrack.
NeedlesneedlesOne or more items to search for. Each ofneedles mustbe either comparable to one element inhaystack, or be itself aforward range with elements comparable with elements inhaystack.
Returns:
A tuple containinghaystack positioned to match one of theneedles and also the 1-based index of the matching element inneedles (0 if none ofneedles matched, 1 ifneedles[0]matched, 2 ifneedles[1] matched...). The first needle to be foundwill be the one that matches. If multiple needles are found at thesame spot in the range, then the shortest one is the one which matches(if multiple needles of the same length are found at the same spot (e.g"a" and'a'), then the left-most of them in the argument listmatches).
The relationship betweenhaystack andneedles simply meansthat one can e.g. search for individualints or arrays ofints in an array ofints. In addition, if elements areindividually comparable, searches of heterogeneous types are allowedas well: adouble[] can be searched for anint or ashort[], and conversely along can be searched for afloator adouble[]. This makes for efficient searches without the needto coerce one side of the comparison into the other's side type.
The complexity of the search isΟ(haystack.length *max(needles.length)). (For needles that are individual items, lengthis considered to be 1.) The strategy used in searching severalsubranges at once maximizes cache usage by moving inhaystack asfew times as possible.
Examples:
import std.typecons : tuple;int[] a = [ 1, 4, 2, 3 ];writeln(find(a, 4));// [4, 2, 3]writeln(find(a, [1, 4]));// [1, 4, 2, 3]writeln(find(a, [1, 3], 4));// tuple([4, 2, 3], 2)// Mixed types allowed if comparablewriteln(find(a, 5, [1.2, 3.5], 2.0));// tuple([2, 3], 3)
RandomAccessRangefind(RandomAccessRange, alias pred, InputRange)(RandomAccessRangehaystack, scope BoyerMooreFinder!(pred, InputRange)needle);
Findsneedle inhaystack efficiently using the Boyer-Moore method.
Parameters:
RandomAccessRangehaystackA random-access range with length and slicing.
BoyerMooreFinder!(pred, InputRange)needleABoyerMooreFinder.
Returns:
haystack advanced such thatneedle is a prefix of it (if no such position exists, returnshaystack advanced to termination).
Examples:
import std.range.primitives : empty;int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];int[] b = [ 1, 2, 3 ];writeln(find(a, boyerMooreFinder(b)));// [1, 2, 3, 4, 5]assert(find(b, boyerMooreFinder(a)).empty);
templatecanFind(alias pred = "a == b")
Convenience function. Like find, but only returns whether or not the searchwas successful.
For more information aboutpred seefind.
See Also:
std.algorithm.comparison.among for checking a value against multiple arguments.
Examples:
const arr = [0, 1, 2, 3];assert(canFind(arr, 2));assert(!canFind(arr, 4));// find one of several needlesassert(arr.canFind(3, 2));assert(arr.canFind(3, 2) == 2);// second needle foundwriteln(arr.canFind([1, 3], 2));// 2assert(canFind(arr, [1, 2], [2, 3]));writeln(canFind(arr, [1, 2], [2, 3]));// 1assert(canFind(arr, [1, 7], [2, 3]));writeln(canFind(arr, [1, 7], [2, 3]));// 2assert(!canFind(arr, [1, 3], [2, 4]));writeln(canFind(arr, [1, 3], [2, 4]));// 0
Examples:
Example using a custom predicate. Note that the needle appears as the second argument of the predicate.
auto words = ["apple","beeswax","cardboard"];assert(!canFind(words,"bees"));assert(canFind!((string elem, string needle) => elem.startsWith(needle))(words,"bees"));
Examples:
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 ="aaa111aaa";string s2 ="aaa222aaa";string s3 ="aaa333aaa";string s4 ="aaa444aaa";const hay = [s1, s2, s3, s4];assert(hay.canFind!(e => e.canFind("111","222")));
boolcanFind(Range)(Rangehaystack)
if (is(typeof(find!pred(haystack))));
Returnstrue if and only ifpred(e) is true for any valuee in the input rangerange. Performs (at most)Ο(haystack.length) evaluations ofpred.
boolcanFind(Range, Element)(Rangehaystack, scope Elementneedle)
if (is(typeof(find!pred(haystack,needle))));
Returnstrue if and only ifneedle can be found in range. PerformsΟ(haystack.length) evaluations ofpred.
size_tcanFind(Range, Needles...)(Rangehaystack, scope Needlesneedles)
if (Needles.length > 1 && is(typeof(find!pred(haystack,needles))));
Returns the 1-based index of the first needle found inhaystack. If no needle is found, then0 is returned.
So, if used directly in the condition of anif statement or loop, the result will betrue if one of the needles is found andfalse if none are found, whereas if the result is used elsewhere, it can either be cast tobool for the same effect or used to get which needle was found first without having to deal with the tuple thatfind returns for the same operation.
RangefindAdjacent(alias pred = "a == b", Range)(Ranger)
if (isForwardRange!Range);
Advancesr until it finds the first two adjacent elementsa,b that satisfypred(a, b). PerformsΟ(r.length)evaluations ofpred.
For more information aboutpred seefind.
Parameters:
predThe predicate to satisfy.
RangerAforward range to search in.
Returns:
r advanced to the first occurrence of two adjacent elements that satisfythe given predicate. If there are no such two elements, returnsr advanceduntil empty.
See Also:
Examples:
int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ];autor =findAdjacent(a);writeln(r);// [10, 10, 9, 8, 8, 7, 8, 9]auto p =findAdjacent!("a < b")(a);writeln(p);// [7, 8, 9]
InputRangefindAmong(alias pred = "a == b", InputRange, ForwardRange)(InputRangeseq, ForwardRangechoices)
if (isInputRange!InputRange && isForwardRange!ForwardRange);
Searches the given range for an element that matches one of the given choices.
Advancesseq by callingseq.popFront until eitherfind!(pred)(choices,seq.front) istrue, orseq becomes empty.PerformsΟ(seq.length * choices.length) evaluations ofpred.
For more information aboutpred seefind.
Parameters:
predThe predicate to use for determining a match.
InputRangeseqTheinput range to search.
ForwardRangechoicesAforward range of possible choices.
Returns:
seq advanced to the first matching element, or until empty if there are nomatching elements.
See Also:
Examples:
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];int[] b = [ 3, 1, 2 ];writeln(findAmong(a, b));// a[2 .. $]
boolfindSkip(alias pred = "a == b", R1, R2)(ref R1haystack, R2needle)
if (isForwardRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack.front,needle.front))));

size_tfindSkip(alias pred, R1)(ref R1haystack)
if (isForwardRange!R1 && ifTestable!(typeof(haystack.front), unaryFun!pred));
Findsneedle inhaystack and positionshaystack right after the first occurrence ofneedle.
If no needle is provided, thehaystack is advanced as long aspred evaluates totrue. Similarly, the haystack is positioned so aspred evaluates tofalse forhaystack.front.
For more information aboutpred seefind.
Parameters:
R1haystackTheforward range to search in.
R2needleTheforward range to search for.
predCustom predicate for comparison of haystack and needle
Returns:
true if the needle was found, in which casehaystack is positioned after the end of the first occurrence ofneedle; otherwisefalse, leavinghaystack untouched. If no needle is provided, it returns the number of timespred(haystack.front) returned true.
See Also:
Examples:
import std.range.primitives : empty;// Needle is found; s is replaced by the substring following the first// occurrence of the needle.string s ="abcdef";assert(findSkip(s,"cd") && s =="ef");// Needle is not found; s is left untouched.s ="abcdef";assert(!findSkip(s,"cxd") && s =="abcdef");// If the needle occurs at the end of the range, the range is left empty.s ="abcdef";assert(findSkip(s,"def") && s.empty);
Examples:
import std.ascii : isWhite;string s ="    abc";assert(findSkip!isWhite(s) && s =="abc");assert(!findSkip!isWhite(s) && s =="abc");s ="  ";writeln(findSkip!isWhite(s));// 2
autofindSplit(alias pred = "a == b", R1, R2)(R1haystack, R2needle)
if (isForwardRange!R1 && isForwardRange!R2);

autofindSplitBefore(alias pred = "a == b", R1, R2)(R1haystack, R2needle)
if (isForwardRange!R1 && isForwardRange!R2);

autofindSplitAfter(alias pred = "a == b", R1, R2)(R1haystack, R2needle)
if (isForwardRange!R1 && isForwardRange!R2);
These functions find the first occurrence ofneedle inhaystack and thensplithaystack as follows.
findSplit returns a tupleresult containingthree ranges.
  • result[0] is the portion ofhaystack beforeneedle
  • result[1] is the portion ofhaystack that matchesneedle
  • result[2] is the portion ofhaystackafter the match.
Ifneedle was not found,result[0] comprehendshaystackentirely andresult[1] andresult[2] are empty.
findSplitBefore returns a tupleresult containing two ranges.
  • result[0] is the portion ofhaystack beforeneedle
  • result[1] is the balance ofhaystack starting with the match.
Ifneedle was not found,result[0]comprehendshaystack entirely andresult[1] is empty.
findSplitAfter returns a tupleresult containing two ranges.
  • result[0] is the portion ofhaystack up to and including thematch
  • result[1] is the balance ofhaystack startingafter the match.
Ifneedle was not found,result[0] is emptyandresult[1] ishaystack.

In all cases, the concatenation of the returned ranges spans theentirehaystack.

Ifhaystack is a random-access range, all three components of the tuple havethe same type ashaystack. Otherwise,haystack must be aforward range andthe type ofresult[0] (andresult[1] forfindSplit) is the same asthe result ofstd.range.takeExactly.
For more information aboutpred seefind.

Parameters:
predPredicate to compare 2 elements.
R1haystackThe forward range to search.
R2needleThe forward range to look for.
Returns:
A sub-type ofstd.typecons.Tuple of the split portions ofhaystack (see above fordetails). This sub-type ofTuple definesopCast!bool, whichreturnstrue when the separatingneedle was found andfalse otherwise.
See Also:
Examples:
Returning a subtype ofstd.typecons.Tuple enablesthe following convenient idiom:
// findSplit returns a tripletif (auto split ="dlang-rocks".findSplit("-")){    writeln(split[0]);// "dlang"    writeln(split[1]);// "-"    writeln(split[2]);// "rocks"}elseassert(0);// findSplitBefore returns 2 rangesif (const split = [2, 3, 2, 3, 4, 1].findSplitBefore!"a > b"([2, 2])){    writeln(split[0]);// [2, 3, 2]// [3, 4] each greater than [2, 2]    writeln(split[1]);// [3, 4, 1]}elseassert(0);
Examples:
import std.range.primitives : empty;auto a ="Carl Sagan Memorial Station";auto r =findSplit(a,"Velikovsky");import std.typecons : isTuple;staticassert(isTuple!(typeof(r.asTuple)));staticassert(isTuple!(typeof(r)));assert(!r);writeln(r[0]);// aassert(r[1].empty);assert(r[2].empty);r =findSplit(a," ");writeln(r[0]);// "Carl"writeln(r[1]);// " "writeln(r[2]);// "Sagan Memorial Station"if (const r1 =findSplitBefore(a,"Sagan")){assert(r1);    writeln(r1[0]);// "Carl "    writeln(r1[1]);// "Sagan Memorial Station"}if (const r2 =findSplitAfter(a,"Sagan")){assert(r2);    writeln(r2[0]);// "Carl Sagan"    writeln(r2[1]);// " Memorial Station"}
Examples:
Usestd.range.only to find single elements:
import std.range : only;writeln([1, 2, 3, 4].findSplitBefore(only(3))[0]);// [1, 2]
Tuple!(ElementType!Range, size_t)minCount(alias pred = "a < b", Range)(Rangerange)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));

Tuple!(ElementType!Range, size_t)maxCount(alias pred = "a < b", Range)(Rangerange)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));
Computes the minimum (respectively maximum) ofrange along with its number ofoccurrences. Formally, the minimum is a valuex inrange such thatpred(a, x) isfalse for all valuesa inrange. Conversely, the maximum isa valuex inrange such thatpred(x, a) isfalse for all valuesainrange (note the swapped arguments topred).
These functions may be used for computing arbitrary extrema by choosingpredappropriately. For corrrect functioning,pred must be a strict partial order,i.e. transitive (ifpred(a, b) && pred(b, c) thenpred(a, c)) andirreflexive (pred(a, a) isfalse). Thetrichotomy property ofinequality is not required: these algorithms consider elementsa andb equal(for the purpose of counting) ifpred puts them in the same equivalence class,i.e.!pred(a, b) && !pred(b, a).
Parameters:
predThe ordering predicate to use to determine the extremum (minimum or maximum).
RangerangeTheinput range to count.
Returns:
The minimum, respectively maximum element of a range together with thenumber it occurs in the range.

LimitationsIf at least one of the arguments is NaN, the result isan unspecified value. Seestd.algorithm.searching.maxElementfor examples on how to cope with NaNs.

Throws:
Exception ifrange.empty.
See Also:
Examples:
import std.conv : text;import std.typecons : tuple;int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];// Minimum is 1 and occurs 3 timeswriteln(a.minCount);// tuple(1, 3)// Maximum is 4 and occurs 2 timeswriteln(a.maxCount);// tuple(4, 2)
autominElement(alias map = (a) => a, Range)(Ranger)
if (isInputRange!Range && !isInfinite!Range);

autominElement(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Ranger, RangeElementTypeseed)
if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void));
Iterates the passed range and returns the minimal element.A custom mapping function can be passed tomap.In other languages this is sometimes calledargmin.

ComplexityO(n) Exactlyn - 1 comparisons are needed.

Parameters:
mapcustom accessor for the comparison key
Rangerrange from which the minimal element will be selected
RangeElementTypeseedcustom seed to use as initial element

PreconditionIf a seed is not given,r must not be empty.

Returns:
The minimal element of the passed-in range.

Note If at least one of the arguments is NaN, the result is an unspecified value.

If you want to ignore NaNs, you can usestd.algorithm.iteration.filter andstd.math.isNaN to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs:
<range>.filter!(a=>!a.isNaN).minElement(<seed>);
If you want to get NaN as a result if a NaN is present in the range, you can usestd.algorithm.iteration.fold andstd.math.isNaN:
<range>.fold!((a,b)=>a.isNaN || b.isNaN ?real.nan : a < b ? a : b);

See Also:
Examples:
import std.range : enumerate;import std.typecons : tuple;writeln([2, 7, 1, 3].minElement);// 1// allows to get the index of an element toowriteln([5, 3, 7, 9].enumerate.minElement!"a.value");// tuple(1, 3)// any custom accessor can be passedwriteln([[0, 4], [1, 2]].minElement!"a[1]");// [1, 2]// can be seededint[] arr;writeln(arr.minElement(1));// 1
automaxElement(alias map = (a) => a, Range)(Ranger)
if (isInputRange!Range && !isInfinite!Range);

automaxElement(alias map = (a) => a, Range, RangeElementType = ElementType!Range)(Ranger, RangeElementTypeseed)
if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void));
Iterates the passed range and returns the maximal element.A custom mapping function can be passed tomap.In other languages this is sometimes calledargmax.

ComplexityO(n) Exactlyn - 1 comparisons are needed.

Parameters:
mapcustom accessor for the comparison key
Rangerrange from which the maximum element will be selected
RangeElementTypeseedcustom seed to use as initial element

PreconditionIf a seed is not given,r must not be empty.

Returns:
The maximal element of the passed-in range.

NoteIf at least one of the arguments is NaN, the result is an unspecified value. Seestd.algorithm.searching.minElement for examples on how to cope with NaNs.

See Also:
Examples:
import std.range : enumerate;import std.typecons : tuple;writeln([2, 1, 4, 3].maxElement);// 4// allows to get the index of an element toowriteln([2, 1, 4, 3].enumerate.maxElement!"a.value");// tuple(2, 4)// any custom accessor can be passedwriteln([[0, 4], [1, 2]].maxElement!"a[1]");// [0, 4]// can be seededint[] arr;writeln(arr.minElement(1));// 1
ElementType!Range[2]extrema(Range)(Ranger)
if (isInputRange!Range && !isInfinite!Range);
Returns an array of the minimum and maximum element inr. Performs< 3n/2 comparisons, unlike the naive< 2n.
Parameters:
RangerThe range to traverse.
Examples:
writeln(extrema([5, 2, 9, 4, 1]));// [1, 9]
RangeminPos(alias pred = "a < b", Range)(Rangerange)
if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));

RangemaxPos(alias pred = "a < b", Range)(Rangerange)
if (isForwardRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));
Computes a subrange ofrange starting at the first occurrence ofrange'sminimum (respectively maximum) and with the same ending asrange, or theempty range ifrange itself is empty.
Formally, the minimum is a valuex inrange such thatpred(a, x) isfalse for all valuesa inrange. Conversely, the maximum is a valuex inrange such thatpred(x, a) isfalse for all valuesa inrange (notethe swapped arguments topred).
These functions may be used for computing arbitrary extrema by choosingpredappropriately. For corrrect functioning,pred must be a strict partial order,i.e. transitive (ifpred(a, b) && pred(b, c) thenpred(a, c)) andirreflexive (pred(a, a) isfalse).
Parameters:
predThe ordering predicate to use to determine the extremum (minimum or maximum) element.
RangerangeTheforward range to search.
Returns:
The position of the minimum (respectively maximum) element of forwardrangerange, i.e. a subrange ofrange starting at the position of itssmallest (respectively largest) element and with the same ending asrange.

LimitationsIf at least one of the arguments is NaN, the result isan unspecified value. Seestd.algorithm.searching.maxElementfor examples on how to cope with NaNs.

See Also:
Examples:
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];// Minimum is 1 and first occurs in position 3writeln(a.minPos);// [1, 2, 4, 1, 1, 2]// Maximum is 4 and first occurs in position 2writeln(a.maxPos);// [4, 1, 2, 4, 1, 1, 2]
ptrdiff_tminIndex(alias pred = "a < b", Range)(Rangerange)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));
Computes the index of the first occurrence ofrange's minimum element.
Parameters:
predThe ordering predicate to use to determine the minimum element.
RangerangeTheinput range to search.

ComplexityΟ(range.length) Exactlyrange.length - 1 comparisons are needed.

Returns:
The index of the first encounter of the minimum element inrange. If therange is empty, -1 is returned.

LimitationsIf at least one of the arguments is NaN, the result is an unspecified value. Seestd.algorithm.searching.maxElement for examples on how to cope with NaNs.

See Also:
Examples:
int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2];// Minimum is 1 and first occurs in position 3writeln(a.minIndex);// 3// Get maximum index with minIndexwriteln(a.minIndex!"a > b");// 2// Range is empty, so return value is -1int[] b;writeln(b.minIndex);// -1// Works with more custom typesstruct Dog {int age; }Dog[] dogs = [Dog(10), Dog(5), Dog(15)];writeln(dogs.minIndex!"a.age < b.age");// 1
ptrdiff_tmaxIndex(alias pred = "a < b", Range)(Rangerange)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front,range.front))));
Computes the index of the first occurrence ofrange's maximum element.

ComplexityΟ(range) Exactlyrange.length - 1 comparisons are needed.

Parameters:
predThe ordering predicate to use to determine the maximum element.
RangerangeTheinput range to search.
Returns:
The index of the first encounter of the maximum inrange. If therange is empty, -1 is returned.

LimitationsIf at least one of the arguments is NaN, the result is an unspecified value. Seestd.algorithm.searching.maxElement for examples on how to cope with NaNs.

See Also:
Examples:
// Maximum is 4 and first occurs in position 2int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2];writeln(a.maxIndex);// 2// Empty rangeint[] b;writeln(b.maxIndex);// -1// Works with more custom typesstruct Dog {int age; }Dog[] dogs = [Dog(10), Dog(15), Dog(5)];writeln(dogs.maxIndex!"a.age < b.age");// 1
templateskipOver(alias pred = (a, b) => a == b)
Skip over the initial portion of the first given range (haystack) that matchesany of the additionally given ranges (needles) fully, orif no second range is given skip over the elements that fulfill pred.Do nothing if there is no match.
Parameters:
predThe predicate that determines whether elements from each respective range match. Defaults to equality"a == b".
Examples:
import std.algorithm.comparison : equal;auto s1 ="Hello world";assert(!skipOver(s1,"Ha"));writeln(s1);// "Hello world"assert(skipOver(s1,"Hell") && s1 =="o world", s1);string[]  r1 = ["abc","def","hij"];dstring[] r2 = ["abc"d];assert(!skipOver!((a, b) => a.equal(b))(r1, ["def"d]), r1[0]);writeln(r1);// ["abc", "def", "hij"]assert(skipOver!((a, b) => a.equal(b))(r1, r2));writeln(r1);// ["def", "hij"]
Examples:
import std.ascii : isWhite;import std.range.primitives : empty;auto s2 ="\t\tvalue";auto s3 ="";auto s4 ="\t\t\t";assert(s2.skipOver!isWhite && s2 =="value");assert(!s3.skipOver!isWhite);assert(s4.skipOver!isWhite && s3.empty);
Examples:
Variadic skipOver
auto s ="Hello world";assert(!skipOver(s,"hello","HellO"));writeln(s);// "Hello world"// the range is skipped over the longest matching needle is skippedassert(skipOver(s,"foo","hell","Hello "));writeln(s);// "world"
Examples:
import std.algorithm.comparison : equal;auto s1 ="Hello world";assert(!skipOver(s1, 'a'));writeln(s1);// "Hello world"assert(skipOver(s1, 'H') && s1 =="ello world");string[] r = ["abc","def","hij"];dstring e ="abc"d;assert(!skipOver!((a, b) => a.equal(b))(r,"def"d));writeln(r);// ["abc", "def", "hij"]assert(skipOver!((a, b) => a.equal(b))(r, e));writeln(r);// ["def", "hij"]auto s2 ="";assert(!s2.skipOver('a'));
Examples:
Partial instantiation
import std.ascii : isWhite;import std.range.primitives : empty;alias whitespaceSkiper =skipOver!isWhite;auto s2 ="\t\tvalue";auto s3 ="";auto s4 ="\t\t\t";assert(whitespaceSkiper(s2) && s2 =="value");assert(!whitespaceSkiper(s2));assert(whitespaceSkiper(s4) && s3.empty);
boolskipOver(Haystack, Needles...)(ref Haystackhaystack, Needlesneedles)
if (is(typeof(binaryFun!pred(haystack.front,needles[0].front))) && isForwardRange!Haystack && allSatisfy!(isInputRange, Needles) && !is(CommonType!(staticMap!(ElementType, staticMap!(Unqual, Needles))) == void));

boolskipOver(R)(ref Rr1)
if (isForwardRange!R && ifTestable!(typeof(r1.front), unaryFun!pred));

boolskipOver(R, Es...)(ref Rr, Eses)
if (isInputRange!R && is(typeof(binaryFun!pred(r.front,es[0]))));
Parameters:
HaystackhaystackTheforward range to move forward.
NeedlesneedlesTheinput ranges representing the prefix ofr1 to skip over.
EsesThe element to match.
Returns:
true if the prefix ofhaystack matches any range ofneedles fully orpred evaluates to true, andhaystack has been advanced to the point past this segment; otherwise false, andhaystack is left in its original position.

NoteBy definition, empty ranges are matched fully and ifneedles contains an empty range,skipOver will returntrue.

uintstartsWith(alias pred = (a, b) => a == b, Range, Needles...)(RangedoesThisStart, NeedleswithOneOfThese)
if (isInputRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles));

boolstartsWith(alias pred = "a == b", R1, R2)(R1doesThisStart, R2withThis)
if (isInputRange!R1 && isInputRange!R2 && is(typeof(binaryFun!pred(doesThisStart.front,withThis.front)) : bool));

boolstartsWith(alias pred = "a == b", R, E)(RdoesThisStart, EwithThis)
if (isInputRange!R && is(typeof(binaryFun!pred(doesThisStart.front,withThis)) : bool));

boolstartsWith(alias pred, R)(RdoesThisStart)
if (isInputRange!R && ifTestable!(typeof(doesThisStart.front), unaryFun!pred));
Checks whether the giveninput range starts with (oneof) the given needle(s) or, if no needles are given,if its front element fulfils predicatepred.
For more information aboutpred seefind.
Parameters:
predPredicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given.
RangedoesThisStartThe input range to check.
NeedleswithOneOfTheseThe needles against which the range is to be checked, which may be individual elements or input ranges of elements.
R2withThisThe single needle to check, which may be either a single element or an input range of elements.
Returns:
0 if the needle(s) do not occur at the beginning of the given range;otherwise the position of the matching needle, that is, 1 if the range startswithwithOneOfThese[0], 2 if it starts withwithOneOfThese[1], and soon.
In the case wheredoesThisStart starts with multiple of the ranges orelements inwithOneOfThese, then the shortest one matches (if there aretwo which match which are of the same length (e.g."a" and'a'), thenthe left-most of them in the argumentlist matches).
In the case when no needle parameters are given, returntrue iff front ofdoesThisStart fulfils predicatepred.
Examples:
import std.ascii : isAlpha;assert("abc".startsWith!(a => a.isAlpha));assert("abc".startsWith!isAlpha);assert(!"1ab".startsWith!(a => a.isAlpha));assert(!"".startsWith!(a => a.isAlpha));import std.algorithm.comparison : among;assert("abc".startsWith!(a => a.among('a', 'b') != 0));assert(!"abc".startsWith!(a => a.among('b', 'c') != 0));assert(startsWith("abc",""));assert(startsWith("abc","a"));assert(!startsWith("abc","b"));writeln(startsWith("abc", 'a',"b"));// 1writeln(startsWith("abc","b","a"));// 2writeln(startsWith("abc","a","a"));// 1writeln(startsWith("abc","ab","a"));// 2writeln(startsWith("abc","x","a","b"));// 2writeln(startsWith("abc","x","aa","ab"));// 3writeln(startsWith("abc","x","aaa","sab"));// 0writeln(startsWith("abc","x","aaa","a","sab"));// 3import std.typecons : Tuple;alias C = Tuple!(int,"x",int,"y");assert(startsWith!"a.x == b"([ C(1,1), C(1,2), C(2,2) ], [1, 1]));writeln(startsWith!"a.x == b"([C(1, 1), C(2, 1), C(2, 2)], [1, 1], [1, 2], [1, 3]));// 2
aliasOpenRight = std.typecons.Flag!"openRight".Flag;
Interval option specifier foruntil (below) and others.
If set toOpenRight.yes, then the interval is open to the right(last element is not included).
Otherwise if set toOpenRight.no, then the interval is closed to the rightincluding the entire sentinel.
Until!(pred, Range, Sentinel)until(alias pred = "a == b", Range, Sentinel)(Rangerange, Sentinelsentinel, OpenRightopenRight = Yes.openRight)
if (!is(Sentinel == OpenRight));

Until!(pred, Range, void)until(alias pred, Range)(Rangerange, OpenRightopenRight = Yes.openRight);

structUntil(alias pred, Range, Sentinel) if (isInputRange!Range);
Lazily iteratesrange until the elemente for whichpred(e,sentinel) is true.
This is similar totakeWhile in other languages.
Parameters:
predPredicate to determine when to stop.
RangerangeTheinput range to iterate over.
SentinelsentinelThe element to stop at.
OpenRightopenRightDetermines whether the element for which the given predicate is true should be included in the resulting range (No.openRight), or not (Yes.openRight).
Returns:
Aninput range that iterates over the original range's elements, but ends when the specified predicate becomes true. If the original range is aforward range or higher, this range will be a forward range.
Examples:
import std.algorithm.comparison : equal;import std.typecons : No;int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5];assert(equal(a.until(7), [1, 2, 4]));assert(equal(a.until(7, No.openRight), [1, 2, 4, 7]));
Copyright © 1999-2025 by theD Language Foundation | Page generated byDdoc on Fri Oct 10 22:10:23 2025

[8]ページ先頭

©2009-2025 Movatter.jp