Problem with Sorting

Mandeep Singh Brar mandeep at
Thu Jan 27 20:30:47 PST 2011


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 < ?  -1: 1;


int main(string[] args) {
	testcl a = new testcl(args[1]);
	testcl b = new testcl(args[2]);
	testcl[] arr = [a,b];
	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/ [0x139ce7]
./testSort() [0x8049751]

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

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

I could not get the problem with the above code.


More information about the Digitalmars-d-learn mailing list