www.digitalmars.com         C & C++   DMDScript  

D - Q: sort array of objects

reply Ant <duitoolkit yahoo.ca> writes:
Is array sort suppose to work for an
array of object?
the prog included outputs:

foreach sort b
foreach sort a
foreach sort z
for sort b
for sort a
for sort z

the wc.d example works for 
int[char[]] dictionary;
... dictionary.keys.sort ...

Ant



import std.string;

class S
{
	char[] name;
	this(char[] name)
	{
		this.name = name;
	}
	
	int cmp(S s)
	{
		// this is never executed
		printf("std.string.cmp(%.*s, %.*s) = %d\n",
			name, s.name,
			std.string.cmp(name, s.name)
			);
		return std.string.cmp(name, s.name);
	}
}

void main()
{
	S[] as;
	as ~= new S("z");
	as ~= new S("a");
	as ~= new S("b");
	
	// I thought this would work...
	foreach(S s ; as.sort)
	{
		printf("foreach sort %.*s\n",s.name);
	}
	
	// or at least this...
	S[] bs = as.dup.sort;
	for ( int i = 0 ; i<bs.length; i++)
	{
		printf("for sort %.*s\n",bs[i].name);
	}
}
Jan 10 2004
parent reply "Vathix" <vathix dprogramming.com> writes:
"Ant" <duitoolkit yahoo.ca> wrote in message
news:pan.2004.01.11.06.35.37.56028 yahoo.ca...
 Is array sort suppose to work for an
 array of object?
...
 int cmp(S s)
... The function is now opCmp.
Jan 11 2004
parent reply Ant <duitoolkit yahoo.ca> writes:
On Sun, 11 Jan 2004 06:35:51 -0500, Vathix wrote:

 "Ant" <duitoolkit yahoo.ca> wrote in message
 news:pan.2004.01.11.06.35.37.56028 yahoo.ca...
 Is array sort suppose to work for an
 array of object?
...
 int cmp(S s)
... The function is now opCmp.
Thank you. (I beg your forgiveness. I simple look into object.d would have shown it) now int opCmp(S s) still doesn't work I have to do: int opCmp(Object s) { return std.string.cmp(name, (cast(S)s).name); } doesn't seem right. Ant
Jan 11 2004
parent reply "Vathix" <vathix dprogramming.com> writes:
 int opCmp(Object s)
 {
 return std.string.cmp(name, (cast(S)s).name);
 }


 doesn't seem right.

 Ant
What I do is make two: int opCmp(RealObject ro) { return comparison; } override int opCmp(Object o) { RealObject ro = cast(RealObject)o; if(!ro) // not correct type return -1; return opCmp(ro); // normal comparison } Plus two for opEquals... Not sure if this is a good way.
Jan 11 2004
parent Ant <duitoolkit yahoo.ca> writes:
On Sun, 11 Jan 2004 10:46:00 -0500, Vathix wrote:

 int opCmp(Object s)
 {
 return std.string.cmp(name, (cast(S)s).name);
 }


 doesn't seem right.

 Ant
hmmm.... maybe it is right... (I'll get breakfast before continuing posting)
 
 
 What I do is make two:
 
 int opCmp(RealObject ro)
 {
     return comparison;
 }
 
 override int opCmp(Object o)
 {
     RealObject ro = cast(RealObject)o;
     if(!ro) // not correct type
         return -1;
     return opCmp(ro); // normal comparison
 }
 
 Plus two for opEquals...
 Not sure if this is a good way.
I guess that's the way to do it. Ant
Jan 11 2004