Using array.sort

Chris Nicholson-Sauls ibisbasenji at gmail.com
Wed Jan 24 19:40:09 PST 2007


Heinz wrote:
> Carlos Santander Wrote:
> 
>> Heinz escribió:
>>> torhu Wrote:
>>>
>>>> Heinz wrote:
>>>>> What does this sort property do? how can i use it? how do i implement opCmp. thanks in advance
>>>> .sort sorts an array, using some default sort order.  If you want to 
>>>> change the order, you implement opCmp.
>>>>
>>>>
>>>> opCmp has got these signatures, think.  It doesn't seem to be documented 
>>>> much:
>>>>
>>>> class C {
>>>>      // the argument is of type Object, not C
>>>>      int opCmp(Object other);
>>>> }
>>>>
>>>> or:
>>>>
>>>> struct S {
>>>>     int opCmp(S other);
>>>> }
>>>>
>>>>
>>>> opCmp() has to return less than zero if it's own object is smaller, more 
>>>> than zero if 'other' is smaller, and zero if they are equal.
>>>>
>>>> You can't define opCmp for any other types, if you want to change the 
>>>> sort order of ints, you have to write a separate sort function.
>>> So, lets assume we have the following class:
>>>
>>> class myclass
>>> {
>>>         char[] cs;
>>> }
>>>
>>> and then we have a dinamic array of myclass, can we sort this array by the cs property?
>> Yes, you would have to write an opCmp that does that.
>>
>> -- 
>> Carlos Santander Bernal
> 
> Hi,
> 
> Do i have to declare opCmp(Object) and it'll do it automatically? or
> Do i have to write the algorithm to sort the classes by the cs property? if so, what's the sense of having a sort property if i have to implement a propietary function, it acts as a link.

opCmp needs only return the sort-order of an object in relation to another given object. 
Using a simpler example:

class Number {
   int i;

   int opCmp (Object obj) {
     if (auto other = cast(Number) obj) {
       return this.i - other.i;
     }
     else {
       throw new Exception("Can only compare Number with another Number.");
     }
   }
}

Otherwise the .sort property would have no idea how to order the objects (there really is 
no generic means to do this).  IIRC, there is/was a default Object.opCmp which compared 
the address of objects, but this is really useless in terms of proper sorting.  (Although 
it does have the usefulness of making all classes available as associative array keys.)

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list