canFind

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see find.

  1. bool canFind(Range haystack)
    template canFind(alias pred = "a == b")
    bool
    canFind
    (
    Range
    )
    (
    Range haystack
    )
    if (
    is(typeof(find!pred(haystack)))
    )
  2. bool canFind(Range haystack, Element needle)
  3. size_t canFind(Range haystack, Needles needles)

Members

Functions

canFind
bool canFind(Range haystack)

Returns true if and only if pred(e) is true for any value e in the input range range. Performs (at most) O(haystack.length) evaluations of pred.

canFind
bool canFind(Range haystack, Element needle)

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
size_t canFind(Range haystack, Needles needles)

Returns the 1-based index of the first needle found in haystack. If no needle is found, then 0 is returned.

Examples

const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));

// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);

assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);

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"));

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")));

See Also

std.algorithm.comparison.among for checking a value against multiple arguments.

Meta