delphi - 对 TDictionary 进行排序

标签 delphi generics sorting dictionary delphi-xe

我对通用集合没有经验。我需要对 TDictionary 进行排序。

type TSearchResult = TPair<Integer,double>;

var
   target_results : TDictionary<Integer, double>;
   session_search_results : array[0..max_searches] of TArray<TSearchResult>;

我正在使用此代码进行排序

   session_search_results[session_search_id]:= target_results.ToArray;
   TArray.Sort<TSearchResult>(session_search_results[session_search_id],
                    TComparer<TSearchResult>.Construct(
                              function(const L, R: TSearchResult): Integer
                              begin
                                 Result := Round(R.Value - L.Value);
                              end
                    ));

为什么我会遇到访问冲突?我做错了什么?

补充:

如果我使用迭代遍历数组

 for i:= 0 to Length(session_search_results[session_search_id])-1 do
      MyDebug(IntToStr(session_search_results[session_search_id][i].Key)+' = value = '
            + FloatToStr(session_search_results[session_search_id][i].Value));

我得到的输出:

Debug Output: ==>CoreSearchText: array length=8<== Process TestApp.exe (2536)
Debug Output: ==>100007 = value = 19,515<== Process TestApp.exe (2536)
Debug Output: ==>100003 = value = 2,4<== Process TestApp.exe (2536)
Debug Output: ==>100005 = value = 12<== Process TestApp.exe (2536)
Debug Output: ==>100008 = value = 2,4<== Process TestApp.exe (2536)
Debug Output: ==>100002 = value = 2,4<== Process TestApp.exe (2536)
Debug Output: ==>100004 = value = 2,4<== Process TestApp.exe (2536)
Debug Output: ==>100009 = value = 40,515<== Process TestApp.exe (2536)
Debug Output: ==>100001 = value = 15<== Process TestApp.exe (2536)

应用排序时,访问冲突会导致应用程序崩溃。阵列似乎没问题。可能是什么原因?谢谢!

最佳答案

这似乎是 XE 中的代码生成错误(XE2 中也存在),并启用了重新声明的通用记录和优化。

该程序重现了该错误:

program Project1;

{$APPTYPE CONSOLE}
{$O+}

uses
  Generics.Collections,
  Generics.Defaults,
  SysUtils;

type
  TSearchResult = TPair<Integer, Integer>;

function Compare(const L, R: TSearchResult): Integer;
begin
  Result := R.Value - L.Value;
end;

var
  values: TArray<TSearchResult>;
begin
  try
    SetLength(values, 3);
    TArray.Sort<TSearchResult>(values, TComparer<TSearchResult>.Construct(Compare));
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

我已将其报告为 QC #106391 .

一个可能的解决方案是将 {$O-} 添加到包含 TArray.Sort 调用的单元中。

关于delphi - 对 TDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012856/

相关文章:

delphi - 如何在Delphis LiveBindings中提取BindSource的对象?

c# - 如何创建一个通用方法来比较任何类型的两个列表。该类型也可以是类的列表

ios - 将列表排序为 TableView 索引的部分

ios - 如何比较数组?还有改变属性?

algorithm - 什么排序算法适合这个 'stream-like' 条件?

mysql - 如何避免对每个查询重复使用 mysql_real_connect()?

delphi - 访问可执行文件中包含的 JCL 调试信息?

Delphi:单击组合框后会出现什么类型的窗口

c# - C# 如何在 C++ 不允许虚拟模板方法的情况下允许虚拟泛型方法?

java - 如何解决通用实例化问题?