在Delphi 2007中对多维数组进行排序 [英] Sorting multidimensional array in Delphi 2007
问题描述
我有一个多维数组,类似于下面描述的数组:
I have a multidimensional array similar to the one described below:
Matrix => array(
[0] => array( [0] => 7, [1] => 'hello' ),
[1] => array( [0] => 3, [1] => 'there' ),
[2] => array( [0] => 1, [1] => 'world' ),
)
我要实现的目标是使用Matrix [i] [0]的值对该数组进行排序.什么是最有效的方法?我研究了递归QuickSort函数的可能性,但是由于我是多维数组,所以它相当复杂.快速排序有很多示例,但是没有一个可以处理字符串数组数组"作为输入的问题.
What I'm trying to achieve is to sort this array using the values of Matrix[i][0]. What would be the most efficient way to do this? I looked into the recursive QuickSort function possibility, but it's rather complicated as I'm multidimensional arrays. There are many examples of quicksort, but none of them handle taking an "Array of Array of String" as an input.
请澄清我的文字是否乱码.我对Delphi还是很陌生.
Please ask for clarification if my text seems gibberish. I'm still fairly new to Delphi.
推荐答案
正如罗布(Rob)在其评论中指出的那样,没有办法同时存储整数和字符串的多维数组(不求助于变体).
As Rob pointed out in his comment, there's no way to have an multi-dimensional array that stores both integers and strings (without resorting to variants).
如果它实际上只是一个包含整数/字符串对的数组,则使用Strings
和Objects
属性将它们存储在TStringList
中会容易得多,然后使用CustomSort
对Object
值:
If it's really just an array containing integer/string pairs, it would be much easier to store them in a TStringList
using the Strings
and Objects
properties, and then use CustomSort
to sort on the Object
values:
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
function MySortProc(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := Integer(List.Objects[Index1]) - Integer(List.Objects[Index2]);
end;
var
SL: TStringList;
i: Integer;
begin
SL := TStringList.Create;
try
for i := 0 to 10 do
SL.AddObject(Format('Item %d', [i]), TObject(Random(i)));
SL.CustomSort(@MySortProc);
for i := 0 to SL.Count - 1 do
WriteLn(Format('%d: %s', [Integer(SL.Objects[i]), SL[i]]));
ReadLn;
finally
SL.Free;
end;
end.
这产生
这篇关于在Delphi 2007中对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!