gpt4 book ai didi

Delphi XE2 不将字符串列表标记为已排序

转载 作者:行者123 更新时间:2023-12-02 06:50:48 25 4
gpt4 key购买 nike

我在 Delphi XE2 中对字符串列表进行排序时遇到问题。这是一个例子:

procedure AddText();
var
StrList: TStringList;
begin
StrList := TStringList.Create();
StrList.Add('Test1');
StrList.Sort();
WriteLn('Sorted: ' + BoolToStr(StrList.Sorted, true)); // Prints "Sorted: false"
StrList.Add('Test2');
StrList.Sort();
WriteLn('Sorted: ' + BoolToStr(StrList.Sorted, true)); // Prints "Sorted: false"
StrList.Add('Test3');
StrList.Free();
end;

据我了解,问题是由于 TStringList.Sorted 从未设置为 true (既不直接设置也不使用 SetSorted)。是我一个人的问题还是bug?

最佳答案

TStringList.SortClasses 单元中没有任何内容会让您期望它更改属性。 TStringList.Sort 方法只需使用默认排序函数调用 CustomSort 即可。它不是列表状态的指示符(已排序或未排序);它只是确定列表是否使用内部排序算法进行排序,并将新项目添加到正确的位置而不是末尾。来自 documentation :

Specifies whether the strings in the list should be automatically sorted.

Set Sorted to true to cause the strings in the list to be automatically sorted in ascending order. Set Sorted to false to allow strings to remain where they are inserted. When Sorted is false, the strings in the list can be put in ascending order at any time by calling the Sort method.

When Sorted is true, do not use Insert to add strings to the list. Instead, use Add, which will insert the new strings in the appropriate position. When Sorted is false, use Insert to add strings to an arbitrary position in the list, or Add to add strings to the end of the list

不过,你一开始就用错了它。只需将所有字符串添加到 StringList 中,然后设置 Sorted := True;。它将正确设置属性值并自动为您调用内部 Sort 方法。

procedure AddText();
var
StrList: TStringList;
begin
StrList := TStringList.Create();
StrList.Add('Test1');
StrList.Add('Test2');
StrList.Add('Test3');
StrList.Sorted := True;
// Do whatever
StrList.Free;
end;

(您尤其不希望在添加每个项目后调用 Sort();这非常慢且效率低下。)

关于Delphi XE2 不将字符串列表标记为已排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12280063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com