You are not logged in.
Hello,
I am try to use the TDynArrayHashed to store a long list of records. And would like to sort the Array base on the record fields. And the sort rule will base on field1, or field2 which is selected by the user.
R1 = record
f1: integer;
f2: string;
f3: double
end
So that how to pass the sort rule to the compare function?
TDynArraySortCompare = function(const A, B): integer;
/// event oriented version of TDynArraySortCompare
TOnDynArraySortCompare = function(const A, B): integer of object;
When I try to add the custom_record_comapre function to the TDynArrayHashed.Init function, The custom_record_comapre function can not be a Object function, so it can not access the sort_rule owned by the Object.
I have to define a global var of the Object or the sort_rule and use it in the custom_record_comapre function? But I have not only one Object different of them may sort by different record filed. Let say Object1 sort rule is record field1, Object2 sort rule is record field2.
Thank you.
Last edited by wqmeng (2023-11-07 06:14:16)
Offline
Just found that the TOnDynArraySortCompare is what I need.
Thanks
Offline
Note that TDynArrayHashed is not meant to be changed once an item is added.
If you sort the array, it will have to recreate the full hash index become some items may have moved during the sort.
Perhaps a plain TDynArray is better.
Note that if you want to search with the same criteria/comparison function than your sort, you can just use a TDynArray then the "Sorted" methods which will work using binary search in O(log(n)) not O(n).
It will be fast enough even with millions of items, and will need no memory nor CPU to maintain the hash index.
Offline
Hello Ab,
Thanks for you note.
Currently I use TObjectDictionary, and I would like to try TDynArrayHashed or TSynDictionary for better performance and if could save some memory.
As you said, that the TDynArrayHashed will not sort when add a new Item to the array? So that it will not re-sort when update the record? When a record is changed and need re-sort, how about use the SortRange for a better performance?
In my case the array will init only once then sort or sort full array when the user change the sort field he selected, and the items will update frequently so it need re-sort when every time a record filed get changed.
Would you advice to try the TDynArrayHashed or TSynDictionary or the plain TDynArray or just stay with TObjectDictionary?
Thank you
Offline
If you really need to the sort the data, just use TDynArray and its FastAddSort method.
Then you could use fast lookup using FastLocateSorted().
No need to use a hash index in that case.
Offline