我有一个TPoint数组.现在我想知道是否有类似的东西:
apts: TArray<TPoint>;
//
if (apts.indexOF(p1) < 0) do smth
Run Code Online (Sandbox Code Playgroud)
所以是否有一些程序实际上搜索数组的某些东西(在这种情况下是点(p1))并返回它的索引?
在TArray静态类Generics.Collections有一个二进制搜索,但没有线性搜索.我填写这样的特殊差距:
type
TArray = class(Generics.Collections.TArray)
public
class function Contains<T>(const Values: array of T; const Item: T;
const Comparer: IEqualityComparer<T>; out ItemIndex: Integer): Boolean;
overload; static;
class function Contains<T>(const Values: array of T; const Item: T;
out ItemIndex: Integer): Boolean; overload; static;
class function Contains<T>(const Values: array of T; const Item: T): Boolean;
overload; static;
class function IndexOf<T>(const Values: array of T; const Item: T;
const Comparer: IEqualityComparer<T>): Integer; overload; static;
class function IndexOf<T>(const Values: array of T; const Item: T): Integer;
overload; static;
end;
class function TArray.Contains<T>(const Values: array of T; const Item: T;
const Comparer: IEqualityComparer<T>; out ItemIndex: Integer): Boolean;
var
Index: Integer;
begin
for Index := 0 to high(Values) do begin
if Comparer.Equals(Values[Index], Item) then begin
ItemIndex := Index;
Result := True;
exit;
end;
end;
ItemIndex := -1;
Result := False;
end;
class function TArray.Contains<T>(const Values: array of T; const Item: T;
out ItemIndex: Integer): Boolean;
begin
Result := Contains<T>(Values, Item, TEqualityComparer<T>.Default, ItemIndex);
end;
class function TArray.Contains<T>(const Values: array of T; const Item: T): Boolean;
var
ItemIndex: Integer;
begin
Result := Contains<T>(Values, Item, ItemIndex);
end;
class function TArray.IndexOf<T>(const Values: array of T; const Item: T;
const Comparer: IEqualityComparer<T>): Integer;
begin
Contains<T>(Values, Item, Comparer, Result);
end;
class function TArray.IndexOf<T>(const Values: array of T; const Item: T): Integer;
begin
Contains<T>(Values, Item, Result);
end;
Run Code Online (Sandbox Code Playgroud)
我的静态类有更多的功能,但这些是你需要的功能.
此代码依赖于适合您的类型的默认相等比较器.对于类似的简单类型就是这种情况TPoint,但是如果您使用默认比较器不足的更复杂类型,请准备好意外.