Searching ranges
Phobos' std.algorithm
module includes search functions that can work on any ranges. It automatically specializes based on type information. Searching a sorted range is faster than an unsorted range.
How to do it…
Searching has a number of different scenarios, each with different methods:
If you want to know if something is present, use
canFind
.Finding an item generically can be done with the
find
function. It returns the remainder of the range, with the located item at the front.When searching for a substring in a string, you can use
haystack.find(boyerMooreFinder(needle))
. This uses the Boyer-Moore algorithm which may give better performance.If you want to know the index where the item is located, use
countUntil
. It returns a numeric index into the range, just like theindexOf
function for strings.Each
find
function can take a predicate to customize the search operation.When you know your range is sorted but the type doesn't already prove it, you may call
assumeSorted
on it...