opStar

Sean Kelly sean at f4.ca
Tue Nov 13 23:01:51 PST 2007


David B. Held wrote:
> Janice Caron wrote:
>> On Nov 13, 2007 6:17 AM, David B. Held <dheld at codelogicconsulting.com> 
>> wrote:
>>> int size[3] = { length, width, height };
>>> std::sort(size + 0, size + 3);
>>>
>>> I do lots of little stuff like this, which is very convenient.
>>
>> In D:
>>
>>     size.sort;
>>
>> Pointers not needed.
> 
> This presumes that the builtin sort knows the ordering I want to use. 
> Let's try this:
> 
> Customer[] list = { Jim, Bob, Fred };
> list.sort;
> 
> Does list get sorted by first name, last name, phone number, SSN, 
> favorite color, or uncle's friend's dog's favorite park?  If I want to 
> define a custom sort that takes an ordering, I can't use the builtin. 
> Now, in D, arrays are first-class objects, so I would just take an array 
> directly...unless I wrote a generic sort algorithm that took iterators 
> instead.  Then I would rather pass array-iterators to the sort algorithm.

Tango has a sort routine that accepts a comparator, and it can be called 
with the exact same syntax as the built-in version.  It even works on 
ranges:

list[0 .. 2].sort( &myCmp );

See:

http://www.dsource.org/projects/tango/browser/trunk/tango/core/Array.d

The great thing about iterators is that they act as a sort of bookmark, 
so the result of an operation can be stored in a generic manner.  But 
algorithms like sorting, searching, and so on, all operate on a range, 
and D has these already in the form of slices.  Assuming that we had 
random access iterators as well, I'd use them to define a slice and 
perform my operation that way rather than pass them in separately.


Sean



More information about the Digitalmars-d mailing list