Custom opCmp for struct array sort

bearophile bearophileHUGS at lycos.com
Fri Nov 28 06:18:20 PST 2008


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