Using array.sort
Derek Parnell
derek at nomail.afraid.org
Wed Jan 24 21:25:16 PST 2007
On Wed, 24 Jan 2007 22:55:57 -0500, Heinz wrote:
> Hi Chris, i still don't get it hahaha. Replace the int in your
> example by a char[] str; How the hell opCmp can compare a string,
> what value of type int should return? thx
This is a good question. It all depends on how you want to define when one
string is less than another.
Here is one definition, just for example purposes.
import std.stdio;
class myclass {
char[] cs;
this(char[] d) { cs = d.dup; }
int opCmp (Object obj)
{
// Strings contain unicode code-points.
// Shorter strings compare "less than" longer strings.
// Equal length strings compare respective unicode code-points.
if (cs.length < (cast(myclass)obj).cs.length)
return -1;
if (cs.length > (cast(myclass)obj).cs.length)
return 1;
if (cs == (cast(myclass)obj).cs)
return 0;
// Ok, so they are different. Now we look at each code-point.
dchar[] temp_self = std.utf.toUTF32(cs);
dchar[] temp_other = std.utf.toUTF32((cast(myclass)obj).cs);
foreach(int i, dchar c; temp_self)
{
dchar oc;
oc = temp_other[i];
if (c < oc)
return -1;
if (c > oc)
return 1;
}
throw new Error("Failed to find difference. Should never happen.");
}
}
void show(myclass[] Data, char[] Title)
{
writefln("\n\n%s\n--------------", Title);
foreach(myclass x; Data)
{
writefln("%s", x.cs);
}
}
void main()
{
myclass[] A;
A ~= new myclass("one");
A ~= new myclass("two");
A ~= new myclass("three");
A ~= new myclass("four");
A ~= new myclass("five");
A ~= new myclass("six");
A ~= new myclass("seven");
A ~= new myclass("eight");
A ~= new myclass("nine");
A ~= new myclass("ten");
show(A, "Before");
A.sort;
show(A, "After");
}
=============
C:\temp>dmd -run test.d
Before
--------------
one
two
three
four
five
six
seven
eight
nine
ten
After
--------------
one
six
ten
two
five
four
nine
eight
seven
three
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
25/01/2007 4:03:16 PM
More information about the Digitalmars-d-learn
mailing list