count

The first version counts the number of elements x in r for which pred(x, value) is true. pred defaults to equality. Performs O(haystack.length) evaluations of pred.

The second version returns the number of times needle occurs in haystack. Throws an exception if needle.empty, as the count of the empty range in any range would be infinite. Overlapped counts are not considered, for example count("aaa", "aa") is 1, not 2.

The third version counts the elements for which pred(x) is true. Performs O(haystack.length) evaluations of pred.

The fourth version counts the number of elements in a range. It is an optimization for the third version: if the given range has the length property the count is returned right away, otherwise performs O(haystack.length) to walk the range.

Note: Regardless of the overload, count will not accept infinite ranges for haystack.

  1. size_t count(Range haystack, E needle)
    size_t
    count
    (
    alias pred = "a == b"
    Range
    E
    )
    (
    Range haystack
    ,)
    if (
    isInputRange!Range &&
    !isInfinite!Range
    &&
    is(typeof(binaryFun!pred(haystack.front, needle)) : bool)
    )
  2. size_t count(R1 haystack, R2 needle)
  3. size_t count(R haystack)
  4. size_t count(R haystack)

Parameters

pred

The predicate to evaluate.

haystack Range

The range to count.

needle E

The element or sub-range to count in the haystack.

Return Value

Type: size_t

The number of positions in the haystack for which pred returned true.

Examples

1 import std.uni : toLower;
2 
3 // count elements in range
4 int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
5 assert(count(a) == 9);
6 assert(count(a, 2) == 3);
7 assert(count!("a > b")(a, 2) == 5);
8 // count range in range
9 assert(count("abcadfabf", "ab") == 2);
10 assert(count("ababab", "abab") == 1);
11 assert(count("ababab", "abx") == 0);
12 // fuzzy count range in range
13 assert(count!((a, b) => toLower(a) == toLower(b))("AbcAdFaBf", "ab") == 2);
14 // count predicate in range
15 assert(count!("a > 1")(a) == 8);

Meta

Suggestion Box / Bug Report