Search code examples
arraysd

Count elements in vector or check whether element is in array in D


How can I check whether an element is in an array or count occurences of a specific element?

I know that I can hack that myself:

int main()
{
  int [] a = [1,2,3,4,3,4,5,6,6,3,3,3];
  assert(count(a,6) == 2);
  assert(contains(a,7) == false);
  return 0;
}

uint count(T)(T[] a, T t){
  uint cnt = 0;
  foreach(elem; a){
    if(elem == t) ++cnt;
  }
  return cnt;
}

bool contains(T)(T[] a, T t){
  foreach(elem; a){
    if(elem == t) return true;
  }
  return false;
}

but there must be a "library-way" to do it!

edit: I just compared std.algorithm's canFind() and my contains() and it turns out, that contains is faster. Strange but true.


Solution

  • For count see: std.algorithm.count.

    For contains: std.algorithm.canFind. For sorted arrays you can use SortedRange (contains method uses binary search).