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

captain_fid bell.hue at gmail.com
Mon Mar 10 08:09:10 PDT 2014


On Sunday, 9 March 2014 at 10:46:26 UTC, Philippe Sigaud wrote:
>>         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?

Thanks for the simple explanation Phillppe. Someone else 
mentioned before not using pointers in D (the loss of array 
goodness like mentioned in Andrei's book). Bad habits...


More information about the Digitalmars-d-learn mailing list