custom opCmp for array sort
New
d-devel at here.com
Fri Nov 28 07:16:41 PST 2008
Small correction, the code I posted works with D1.0 but not with D2.0. What do I need to change to make it work with D 2.0?
is it better to use D 2 or D 1?
sorry for crossposting, I started my questions on the D group but I was instructed to ask here.
thanks
New Wrote:
> Hello,
>
> I originally posted this question to the wrong group, I am trying here as suggested.
>
> 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
> --------------------------------------------------------------------
> Code cleaned up in d.lang group (my code was a bit messy)
>
> import std.string: find, cmp;
> import std.stdio: writefln;
>
> struct Path {
> string thePath;
>
> int opCmp(Path other) {
> int pos;
> string a, b;
>
> pos = find(this.thePath, "=");
> if (pos > -1)
> a = this.thePath[0 .. pos];
> else
> a = this.thePath;
>
> pos = find(other.thePath, "=");
> if (pos > -1)
> b = other.thePath[0 .. pos];
> else
> b = other.thePath;
>
> return cmp(a, b);
> }
> }
>
> void main() {
> string[][Path] contents = [
> Path("/BBB=/other_dir"): ["aa","bb","cc","dd"],
> Path("/AAA"): ["aa","bb","cc","dd"],
> Path("/BB2=/hello") : ["aa","bb","cc","dd"]
> ];
>
> foreach (item; contents.keys.sort)
> writefln(item.thePath);
> }
More information about the Digitalmars-d-learn
mailing list