Reputation: 8958
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.
Upvotes: 1
Views: 95
Reputation: 6432
For count see: std.algorithm.count
.
For contains: std.algorithm.canFind
. For sorted arrays you can use SortedRange
(contains
method uses binary search).
Upvotes: 1