On Tuesday, 12 November 2013 at 15:51:53 UTC, bearophile wrote:
Daniel Davidson:

Is there a way to search an array I know is ordered by date by only supplying date?

You can use a map to perform a projection:


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

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 });

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

    sarr
    .assumeSorted!q{ a.date < b.date }
    .lowerBound(needle)
    .writeln;

    sarr.writeln;

    sarr
    .map!(s => s.date)
    .assumeSorted
    .lowerBound(Date(2000, 2, 1))
    .writeln;
}


Output:

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

Bye,
bearophile

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?

Thanks
Dan

Reply via email to