Binary search in structs
w0rp via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Apr 5 16:15:03 PDT 2015
On Sunday, 5 April 2015 at 23:06:27 UTC, FreeSlave wrote:
> I have array of structs sorted by specific field. How can I
> perform binary search using this field as a key?
>
> Currently I ended up with this, but it gives error:
>
> struct S
> {
> int i;
> string s;
> }
>
> import std.range;
>
> void main(string [] args)
> {
> S[] structs = [{1,"hello"}, {2,"world"}, {3, "!"}];
> //sorted by i
>
> auto sortedRange = assumeSorted!(function bool(ref const S
> item, int needle) {
> return item.i < needle;
> })(structs);
>
> sortedRange.trisect(2); //compilation error
> }
I believe you have to pass trisect a value of S. So S(2, "")
would do here, I suppose.
More information about the Digitalmars-d-learn
mailing list