D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 3249 - sort and setIntersection on array of struct or class
Summary: sort and setIntersection on array of struct or class
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: x86 Windows
: P2 normal
Assignee: Andrei Alexandrescu
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2009-08-12 16:15 UTC by Jesse Phillips
Modified: 2015-06-09 01:28 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Jesse Phillips 2009-08-12 16:15:28 UTC
If you create an array of struct or class, sorting does not work for std.algorthm.sort

The error from using sort:

    C:\opt\dmd\windows\bin\..\..\src\phobos\std\algorithm.d(3620): Error: static assert  "Invalid predicate passed to sort: a < b"

The error from using setIntersection:

    C:\opt\dmd\windows\bin\..\..\src\phobos\std\functional.d(191): Error: static assert  "Bad binary function q{a < b}. You need to use a valid D expression using symbols a of type S and b of type S."

The code used:

    import std.algorithm;
    import std.stdio;

    struct S {
        string label;

        int opCmp(S s2) {
            if(label < s2.label)
                return -1;
            if(label > s2.label)
                return 1;
            else return 0;
        }
    }

    void main() {
        auto s1 = new S[2];
        auto s2 = new S[2];

        s1[0].label = "fish";
        s1[1].label = "bar";
        s2[0].label = "foo";
        s2[1].label = "fish";

        // Comment out to get setInterseciton error
        sort(s1);

        foreach(str; setIntersection(s1,s2))
            writeln(str);
    }
Comment 1 Andrei Alexandrescu 2009-08-12 16:21:53 UTC
This is because the default comparison is passed as a string, which does not see the definition of the struct. I'll change that to a function.