On Saturday, 8 March 2014 at 18:08:44 UTC, captain_fid wrote:
import std.container: find, equal, empty;
import std.container : SList;

struct c
{
        int idx;
        string name;
}

c[] clist = [ {1, "name1"}, {2, "name2"}, { 3, "name3" } ];
// c* clist = [ {1, "name1"}, {2, "name2"}, { 3, "name3" } ];

int
main()
{
        // Case-insensitive find of a string
        string[] s = [ "Hello", "world", "!" ];
        assert(!find!("toLower(a) == b")(s, "hello").empty);

assert(!find!("toLower(a) == b")(clist.name, "name2").empty);
        return 0;
}

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.

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.

Sorry for the basics...


import std.container;
import std.algorithm;
import std.array;
import std.range;
import std.stdio;

struct C
{
   int idx;
   string name;
   bool opEquals()(auto ref const C v) const {
      return v.idx == this.idx;
   }
   int opCmp(ref const C v) {
      return v.idx == this.idx;
   }
}


int main()
{
   C[] d = [ {1, "name1"}, {2, "name2"}, { 3, "name3" } ];

   auto r = assumeSorted(d);
   assert(r.canFind(C(3, "")));
   assert(!r.canFind(C(32,"")));
   writeln( r.find(C(2, "")));
   return 0;
}

// yields ....
//  [C(2, "name2"), C(3, "name3") ]

Well, I see that both opEquals and opCmp needed to be overridden.

But it's odd that C(3, "name3") is returned as well as C(2, "name2"). And the "" is ugly...

Any suggestions would be helpful.

Reply via email to