'in' for arrays?
Derek Parnell
derek at nomail.afraid.org
Thu Dec 7 14:55:34 PST 2006
On Thu, 07 Dec 2006 22:26:15 +0000, Stewart Gordon wrote:
Is this useful to someone?
// -----------------
template ContainsFrom (T)
{
// Return 'index' if 'element' found in 'array' otherwise return -1
int ContainsFrom(T[] pArray, T pElement, int pIndex)
{
if (pIndex >= 0)
{
while (pIndex < pArray.length)
{
if (pElement == pArray[pIndex])
return pIndex;
pIndex++;
}
}
return -1; // Not Found
}
}
template Contains (T)
{
int Contains(T[] pArray, T pElement)
{
return ContainsFrom(pArray,pElement,0);
}
}
unittest
{
int[] X;
X ~= 3;
X ~= 2;
X ~= 6;
X ~= 8;
X ~= 1;
assert(X.Contains(8) == 3);
assert(X.Contains(3) == 0);
assert(X.Contains(-1) == -1);
assert(X.Contains(99) == -1);
assert(X.ContainsFrom(8,4) == -1);
assert(X.ContainsFrom(8,2) == 3);
char[] Y = "qwerty";
assert(Y.Contains('a') == -1);
assert(Y.Contains('q') == 0);
assert(Y.Contains('t') == 4);
assert(Y.Contains('z') == -1);
}
// -------------
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
8/12/2006 9:52:26 AM
More information about the Digitalmars-d
mailing list