Custom opCmp for struct array sort
New
d-devel at here.com
Fri Nov 28 05:47:00 PST 2008
Hello,
I am new with D and am stuck with something I hope somebody can help me with it.
I am trying sort an array of paths which can take the two following forms:
/usr ---> normal path
/bin=/other/bin ---> a symlink
When I sort these paths, in the case of symlinks I want to ignore the right hand side and I just use the path before the "=" sign.
The array docs for DMD 2.0, say that can create a structure and create a opCmp function to cutomise the way sort works. I have tried this but calling .sort does not seem to pick-up my custom opCmp.
Any help would be very appreciated. I am including the code below
Thanks a lot
--------------------------------------------------------------------
struct Path {
invariant(char) [] thePath;
int opCmp(Path p) {
int pos;
invariant(char) [] a;
invariant(char) [] b;
if( (pos=find(this.thePath, RegExp("="))) > -1 ) {
a = this.thePath[0 .. pos];
} else {
a = this.thePath;
}
if( (pos=find(p.thePath, RegExp("="))) > -1 ) {
b = p.thePath[0 .. pos];
} else {
b = p.thePath;
}
int cosa = std.string.cmp(a, b);
writefln( a, " comp ", b, "=", cosa);
return std.string.cmp(a, b);
}
}
int main(char[][] args) {
char[][][Path] contents;
Path one;
one.thePath = "/002=/other_dir";
contents[one] = cast(char[][])["aa","bb","cc","dd"];
Path two;
two.thePath = "/001";
contents[two] = cast(char[][])["aa","bb","cc","dd"];
foreach(item; contents.keys.sort) {
writefln( item.thePath );
}
return 0;
}
More information about the Digitalmars-d
mailing list