linear search using 'find' on an array of structs?

Philippe Sigaud philippe.sigaud at gmail.com
Sun Mar 9 00:00:34 PST 2014


>         assert(!find!("toLower(a) == b")(s, "hello").empty);
>
>         assert(!find!("toLower(a) == b")(clist.name, "name2").empty);
>

But clist is an array of c's, it has no `.name` field by itself. So, put
the `.name` call inside the comparator:


 assert( find!("toLower(a.name) == b")(clist <http://clist.name/>*,*
 "name2").empty);

This gives me this code:

import std.algorithm: find;
import std.array: empty;
import std.uni: toLower;

struct C // Use UpperCase for you user-defined types
{
  int idx;
  string name;
}

C[] clist = [ {1, "name1"}, {2, "name2"}, { 3, "name3" } ];

void main() // no need to return 0
{
  auto target = clist.find!((a,b) => toLower(a.name) == b)("name2");
  assert(!target.empty);
}

Using UFCS (Universal Function Call Syntax) to tranform f(a,b) into a.f(b).
I used it on `find`.



> I went looking to replace several foreach statements. Can 'find' (in
> understand it's just a linear search) be used on an array of structures
> like above.
>

Sure, as long as you tell it how you will get the info from the range (it
defaults to simple equality).



>
> Example pulled and modified. Above code gives me (naturally) -
>   ... no property 'name' for type 'cp[]'.
>
> Interestingly, I had accidentally coded the commented out line before and
> it compiles correctly but will (as you guessed it) fail.
>

I never use pointers in D. I suppose the `.name` call is propagated to the
array elements?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20140309/9968e6ea/attachment.html>


More information about the Digitalmars-d-learn mailing list