排序数组的最佳方法 [英] Best way to sort an array
问题描述
说我有,我想根据记录中的一个字段排序记录的数组。什么是实现这一目标的最佳途径?
TExample =记录
SortOrder的整数;
SomethingElse:字符串;
结束;VAR SomeVar:TExample的阵列;
您可以添加指向数组的一个从TList
,然后调用<$ C $的元素C> TList.Sort 与比较功能,并最终创建一个新的数组,并在所需顺序值复制出从TList。
不过,如果你使用的下一个版本,D2009,还有一个新的集合库,可以排序数组。它带有一个可选的的IComparer&LT; TExample&GT;
执行自定义排序订单。这是行动的具体情况:
TArray.Sort&LT; TExample&GT;(SomeVar,TDelegatedComparer&LT; TExample&GT; .Construct(
函数(const的左,右:TExample):整数
开始
结果:= TComparer&LT;整数GT; .Default.Compare(Left.SortOrder,Right.SortOrder);
结束));
Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
You can add pointers to the elements of the array to a TList
, then call TList.Sort
with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.
However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer<TExample>
implementation for custom sorting orders. Here it is in action for your specific case:
TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(
function(const Left, Right: TExample): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);
end));
这篇关于排序数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!