[fpc-pascal] Elegant way to switch sort mechanism in TSortedCollection?

Philippe philippe at quarta.com.br
Wed Mar 12 20:30:43 CET 2014


 

using the example at
http://acm.msu.ru/mkoshp/fpc/rtl/objects/tsortedcollection.html 

may
something this way ... 

Type
TMethod = ( method_type_1, method_type_2,
method_type_3); 

PMySortedCollection = ^TMySortedCollection;
TMySortedCollection = Object(TSortedCollection)
 method : TMethod;

Function Compare (Key1,Key2 : Pointer): Sw_integer; virtual; 
 procedure
setMethod( const m : TMethod);
end; 

Implementation 

Uses MyObject;


Function TMySortedCollection.Compare (Key1,Key2 : Pointer)
:sw_integer; 

begin 
 case method of

 method_type_1:
Compare:=PMyobject(Key1)^.GetField - PMyObject(Key2)^.GetField;


method_type_2: Compare:=PMyobject(Key2)^.GetField -
PMyObject(Key1)^.GetField;

 method_type_3:
Compare:=PMyobject(Key1)^.GetField - 2 * PMyObject(Key2)^.GetField; 


end;
end;

procedure TMySortedCollection.setMethod( const m :
TMethod);

begin 

 method := m; 

 .... 

end; 

Em 12.03.2014 15:51,
Jim Leonard escreveu: 

> I'm working on a project that utilizes a
TSortedCollection to help keep 
> items sorted during processing. There
is a need to re-sort the 
> collection by different criteria on-demand
as the program runs. 
> (Different sort orders are an integral part of
the processing.)
> 
> Unless I'm missing something, TSortedCollection
lacks the ability to 
> change the Compare method after initialization
and/or explicitly re-sort 
> the collection on-demand. I was planning on
handling each new (re)sort by:
> 
> 1. Initializing a new
TSortedCollection with the desired Compare method
> 2. Copying the
contents from the old collection to the new one
> 3. Swap collection
pointers; destroy the old collection.
> 
> This works without much
penalty because the collection will never get 
> beyond a reasonable
size, but the implementation makes me cringe. Is 
> there a more elegant
way to do this (without writing my own sort 
> routines for a plain
TCollection)?

 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140312/444bd1f9/attachment.html>


More information about the fpc-pascal mailing list