2012-01-19 39 views
1

我需要一些建議來解決這個問題。我有這樣的數據結構:結構化數組和搜索

type 
    QmyArray = array of integer; 
    PmyArray = record 
    element: Qmyarray; 
    value: integer; 
    end; 
    TMyArray = array of Pmyarray; 

var 
    myarray: tmyArray; 
    myvalue: qmyarray; 

我正確設置myarray中的所有值,並myarray.element的所有值都正確排序,這是好的。我遇到的問題是我想在myarray中搜索myvalue並獲得價值。 搜索,我用的binarySearch寫:

tarray.BinarySearch(myarray, myvalue, index); 

,當然它不工作。因爲我明白,需要定製的比較器,所以我寫:

function CompareB(const Left, Right: integer): Integer; 
begin 
    if Left < Right then 
    Result := -1 
    else if Left > Right then 
    Result := 1 
    else 
    Result := 0; 
end; 

function CompareA(const Left, Right: pmyarray): Integer; 
var 
    iIndex: Integer; 
begin 
    Result := CompareB(Left.element[0], Right.element[0]); 
    for iIndex := 1 to High(Right.element) do 
    if Result = 0 then 
     Result := CompareB(Left.element[iIndex], Right.element[iIndex]); 
end; 

,並嘗試:

tarray.BinarySearch(myarray, myvalue, index, TComparer<Pmyarray>.Construct(CompareA)); 

但在這種情況下,我收到此錯誤:

[DCC Error] Project1.dpr(98): E2250 There is no overloaded version of 'BinarySearch' that can be called with these arguments

和我不不明白我犯了什麼錯誤。

我該如何解決?

+0

這看起來像一本字典給我...... –

+0

是的,事實上。看幾天前的例子,我認爲這樣比較好。只是我有一些疑問。因爲數組有很多元素(以百萬爲單位)用於讀取所有數據,我需要4-5秒,並且使用列表直到20-25秒。如果字典用更少的時間幫助我,那對我來說也是非常好的。 –

回答

4

您有一個唯一的錯誤,myvalue變量的類型應該是PMyArray,而不是QmyArray。下一次遇到此類問題時,請嘗試使用TArray.BinarySearch的長手版本,以便Code Insight實際顯示有意義的類型名稱。

當你寫:

TArray.BinarySearch(myarray, myvalue, index, iComparer) 

編譯器需要猜測你的陣列從參數的類型。如果您錯過了myarraymyvalue的類型,那麼編譯器無法確定您真正想要的內容,並且代碼洞察力無法真正向您顯示您想要的內容。但是你可以告訴它你想要操作陣列的類型,使用此語法給它一個手:

TArray.BinarySearch<PmyArray>(myarray, myvalue, index, iComparer) 

這樣,編譯器知道你打算處理的PmyArray數組。代碼洞察力也知道它並向您顯示它所需的參數的確切類型。

這工作:

program Project9; 

{$APPTYPE CONSOLE} 

uses 
    SysUtils, Generics.Collections, Generics.Defaults; 

type 
    QmyArray = array of Integer; 
    PmyArray = record 
    element: QmyArray; 
    value: Integer; 
    end; 
    TMyArray = array of PmyArray; 

var myarray: TMyArray; 
    myvalue: PmyArray; 
    FoundIndex: Integer; 

function CompareB(const Left, Right: integer): Integer; 
begin 
    if Left < Right then 
    Result := -1 
    else if Left > Right then 
    Result := 1 
    else 
    Result := 0; 
end; 

function CompareA(const Left, Right: pmyarray): Integer; 
var 
    iIndex: Integer; 
begin 
    Result := CompareB(Left.element[0], Right.element[0]); 
    for iIndex := 1 to High(Right.element) do 
    if Result = 0 then 
     Result := CompareB(Left.element[iIndex], Right.element[iIndex]); 
end; 

begin 
    TArray.BinarySearch<PmyArray>(myarray, myvalue, FoundIndex, TComparer<PmyArray>.Construct(CompareA)); 
end. 
+0

你好,你的例子解決了這個問題,但只是部分;在輸入中,我有一個類型爲qmyarray的變量,我需要在數組中搜索此值以獲取與數組關聯的值。 –

+1

您實際上沒有選擇,'TArray.BinarySearch '在'T'數組中搜索'T'類型的值。在你的情況下,你只需要聲明一個類型爲「PMyArray」的變量,將它初始化爲你所需要的元素字段並搜索它。 –