Custom opCmp for struct array sort
New
d-devel at here.com
Fri Nov 28 06:32:31 PST 2008
Hello,
Thanks for cleaning up the code, I was getting a bit annoyed with the all the invariants, but I did not know how to get rid of them.
I tried your version but still the opCmp is not called :(
I will try on D.learn
thanks very much
bearophile Wrote:
> New:
> > 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.
>
> This may work (D1), I have cleaned up your code some:
>
> 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("/002=/other_dir"): ["aa","bb","cc","dd"],
> Path("/001"): ["aa","bb","cc","dd"],
> Path("/002=/hello") : ["aa","bb","cc","dd"]
> ];
>
> foreach (item; contents.keys.sort)
> writefln(item.thePath);
> }
>
> Note that you may not need it, because the part before = is on the left, so just sorting the strings may give you the order you need, without using any opCmp.
>
> For other similar questions the D.learn newsgroup is fitter.
>
> Bye,
> bearophile
More information about the Digitalmars-d
mailing list