Bug 3249 – sort and setIntersection on array of struct or class
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2009-08-12T16:15:00Z
Last change time
2015-06-09T01:28:05Z
Assigned to
andrei
Creator
Jesse.K.Phillips+D
Comments
Comment #0 by Jesse.K.Phillips+D — 2009-08-12T16:15:28Z
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 by andrei — 2009-08-12T16:21:53Z
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.