Best way to check for an element in an array?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 22 06:47:43 PDT 2014


On Mon, 21 Apr 2014 23:25:39 -0400, Taylor Hillegeist  
<taylorh140 at gmail.com> wrote:

> So I find myself Doing this kind of thing very frequently. I have a  
> Array of Somethings and i want to see if "something specific" is inside  
> the array. I wrote a template for it. but is this the best way to do  
> this kind of thing. I feel like it doesn't help with readability. Is  
> there a better way? Maybe i missed something in the std library.
>
> import std.stdio;
>

Change this:

> template FNDR(T){

To  this:

template isIn(T) {

>      bool isIn(T Element, T[] Array){
>          bool rtn=false;
>          foreach(T ArrayElement; Array){
>              if(Element==ArrayElement){
>                  rtn=true;
>              }
>          }
>      return rtn;
>      }
> }
>
> void main(string[] args)
> {
>      int[3] stuff=[0,1,2];
>      if (FNDR!int.isIn(2,stuff))

now: if(isIn(2, stuff))

see implicit function template instantiation (IFTI) in docs.

Also, using UFCS (Unified Function Call Syntax (I think)), we can do:

if(2.isIn(stuff))

Or if you swap the parameters, and perhaps rename your template/function:

if(stuff.contains(2))

>      {
>          writeln("Hello World!");
>      }
> }

-Steve


More information about the Digitalmars-d-learn mailing list