The in operator and normal arrays
Derek Parnell
derek at nomail.afraid.org
Wed Apr 25 16:40:10 PDT 2007
On Thu, 26 Apr 2007 01:30:46 +0200, Myron Alexander wrote:
> Hello.
>
> I'm curious as to the reason for why the in operator only works with
> associative arrays. I am working on a program where having an in
> operator for a normal array would be useful. eg:
>
> if ("string" in ["string1", "string2", "string3", ...]) {
> do something
> }
>
> Is there some other way to do this in the language without resorting to
> a function or class method call?
>
No. The D programming language does not contain a reserved word or built-in
function to scan through an array other than Associative Arrays.
The simplest is just a function call ...
if (container.contains(elem) == true) {
// do something
}
where contains is something along the lines of ...
bool contains(T)(T[] container,T elem)
{
foreach(e; container)
if (e == elem) return true;
return false;
}
Unless you know some details about the internal ordering of the array
elements, a simple linear scan is all that can really be done.
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Justice for David Hicks!"
26/04/2007 9:33:19 AM
More information about the Digitalmars-d
mailing list