我需要一个可以排序的字典。我认为Spring4D TOrderedDictionary是实现这一功能的类,但我无法使其正常工作:排序不起作用。
我编写了一个小的测试程序来展示我的问题:
program Spring4DOrderedDictionaryTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults,
Spring.Collections;
type
TKey = TPair<Double, Integer>;
TValue = Integer;
TEqComparer = class(TEqualityComparer<TKey>, IEqualityComparer<TKey>)
function Equals(const Left, Right: TKey): Boolean; reintroduce;
function GetHashCode(const Value: TKey): Integer; reintroduce;
end;
TAComparer = class(TComparer<TPair<TPair<Double, Integer>, Integer>>, IComparer<TPair<TKey, TValue>>)
function Compare(const Left, Right: TPair<TKey, Integer>): Integer; override;
end;
function TEqComparer.Equals(const Left, Right: TKey): Boolean;
begin
Result := Abs(Left.Key - Right.Key) < 1E-9;
if Result then
Result := Left.Value = Right.Value;
end;
function TEqComparer.GetHashCode(const Value: TKey): Integer;
begin
Result := Round(Value.Key * 1E6) + Value.Value;
end;
function TAComparer.Compare(const Left, Right: TPair<TKey, Integer>): Integer;
begin
if Abs(Left.Key.Key - Right.Key.Key) < 1E-9 then begin
if Left.Key.Value < Right.Key.Value then
Result := -1
else if Left.Key.Value > Right.Key.Value then
Result := 1
else
Result := 0;
end
else begin
if Left.Key.Key < Right.Key.Key then
Result := -1
else if Left.Key.Key > Right.Key.Key then
Result := 1
else
Result := 0;
end;
end;
const
SEG_START = 0;
SEG_END = 1;
var
Events : IOrderedDictionary<TKey, TValue>;
Event : TPair<TKey, TValue>;
EqComparer : IEqualityComparer<TKey>;
AComparer : IComparer<TPair<TKey, TValue>>;
begin
EqComparer := TEqComparer.Create;
AComparer := TAComparer.Create;
Events := TCollections.CreateOrderedDictionary<TKey, TValue>;//(EqComparer);
// Put some data into the dictionary
Events.Add(TKey.Create(-7.41, SEG_START), 0);
Events.Add(TKey.Create(-1.3, SEG_END ), 0);
Events.Add(TKey.Create(-4.0, SEG_START), 1);
Events.Add(TKey.Create(-4.21, SEG_END ), 1);
Events.Add(TKey.Create(-4.92, SEG_START), 2);
Events.Add(TKey.Create(-4.26, SEG_END ), 2);
Events.Add(TKey.Create(-4.55, SEG_START), 3);
Events.Add(TKey.Create(-2.54, SEG_END ), 3);
Events.Add(TKey.Create(-3.70, SEG_START), 4);
Events.Add(TKey.Create(-3.70, SEG_END ), 4);
// Sort the dictionary
Events.Ordered(AComparer);
// Show the values in dictionary (Should be sorted -7.41 first and -1.3 last)
for Event in Events do
WriteLn(Format(' %5.2f %d %d', [Event.Key.Key, Event.Key.Value, Event.Value]));
ReadLn;
end.
上述代码按添加顺序显示值,而不是我认为AComparer应该创建的顺序。
我尝试使用相等比较器创建OrderedDictionary,但没有改变。
感谢任何帮助。