排序数组的最佳方法 [英] Best way to sort an array

查看:47
本文介绍了排序数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组记录,我想根据记录中的一个字段对其进行排序.实现这一目标的最佳方法是什么?

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;

推荐答案

您可以将指向数组元素的指针添加到TList,然后调用TList.Sort用一个比较函数,最后创建一个新数组,并按照需要的顺序将值从TList中拷贝出来.

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.

但是,如果您使用的是下一个版本 D2009,则有一个新的集合库可以对数组进行排序.它采用可选的 IComparer 实现来自定义排序顺序.这是针对您的特定情况的操作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆