Problem with Sorting

Mandeep Singh Brar mandeep at brars.co.in
Thu Jan 27 20:30:47 PST 2011


Hi,

I am facing the following problems with sorting. .

module testSort;

import std.stdio;
import std.algorithm;

class testcl {
	public string name;
	this(string na) { name=na; }
	public string toString() {
		return name;
	}
	public int opCmp(testcl b) {

		return name < b.name ?  -1: 1;
	}

}

int main(string[] args) {
	testcl a = new testcl(args[1]);
	testcl b = new testcl(args[2]);
	testcl[] arr = [a,b];
	writeln(arr);
	sort!("a>b")(arr);
	writeln(arr);
	return 0;
}

I get the following input when i run this program as:

./testSort te2 test2
[te2, test2]
[test2, te2]


./testSort test1 test2
[test1, test2]
[test2, test1]

which is as desired.. But randomly with a few strings it gives me a range violation as:


./testSort test2 te1
[test2, te1]
core.exception.RangeError at std.algorithm(5293): Range violation
----------------
./testSort() [0x80599d6]
./testSort() [0x8050ca6]
./testSort() [0x8052b26]
./testSort() [0x804d39d]
./testSort() [0x804d2a8]
./testSort() [0x804ce3a]
./testSort() [0x8049919]
./testSort() [0x8050e66]
./testSort() [0x8050dc0]
./testSort() [0x8050eaa]
./testSort() [0x8050dc0]
./testSort() [0x8050d66]
/lib/libc.so.6(__libc_start_main+0xe7) [0x139ce7]
./testSort() [0x8049751]

The problem gets corrected if i write the comparison function as :

	public int opCmp(testcl b) {
		if(name == b.name) return 0;
		return name < b.name ?  -1: 1;
	}

I could not get the problem with the above code.

Thanks
Mandeep


More information about the Digitalmars-d-learn mailing list