custom opCmp for array sort

Gide Nwawudu gide at btinternet.com
Sat Nov 29 04:21:09 PST 2008


On Fri, 28 Nov 2008 13:58:28 -0500, Kagamin <spam at here.lot> wrote:

>just found it accidentally
>http://d.puremagic.com/issues/show_bug.cgi?id=1309

Yep, this issue prevents Path.opCmp from being called. The version
below works.


import std.string: find, cmp;
import std.stdio: writefln;
import std.algorithm : sort;

struct Path {
    string thePath;

    int opCmp(Path other) {
    	writefln("Path.opCmp");
        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"]
    ];
    
    Path[] myPaths = contents.keys.dup;
    //myPaths.sort; // Does not call Path.opCmp
    sort(myPaths); // calls Path.opCmp
	
    foreach (item; myPaths)
        writefln(item.thePath);
}


More information about the Digitalmars-d-learn mailing list