how use lowerBound with just sorting key, not complete values

bearophile bearophileHUGS at lycos.com
Tue Nov 12 08:34:29 PST 2013


Daniel Davidson:

> Yes, but that is only giving the dates. I want the actual array 
> elements. Suppose S is a large object with lots of extra fields 
> in addition to `string foo`. There should be a way to pull out 
> the lower bound based on a date without creating a needle (S). 
> Maybe lowerBound is not the right function?

Second try:

import std.stdio, std.range, std.datetime, std.algorithm,
        std.array, std.typecons;

struct S {
     Date date;
     string foo;
}

void main() {
     auto sarr = [S(Date(2000, 1, 1), "x"),
                  S(Date(2000, 2, 1), "a"),
                  S(Date(2000, 3, 1), "foo")];
     assert(sarr.isSorted!q{ a.date < b.date });

     sarr.writeln;
     auto needle = S(Date(2000, 2, 1));

     sarr
     .map!(s => s.date)
     .zip(sarr.length.iota)
     .assumeSorted!q{ a[0] < b[0] }
     .lowerBound(tuple(needle.date, 0))
     .map!(p => sarr[p[1]])
     .writeln;
}


Output:

[S(2000-Jan-01, "x"), S(2000-Feb-01, "a"), S(2000-Mar-01, "foo")]
[S(2000-Jan-01, "x")]

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list