Dim*_*ats 10 arrays delphi indexing compare
我有3个数组,例如:
const
A: Array[0..9] of Byte = ($00, $01, $AA, $A1, $BB, $B1, $B2, $B3, $B4, $FF);
B: Array[0..2] of Byte = ($A1, $BB, $B1);
C: Array[0..2] of Byte = ($00, $BB, $FF);
Run Code Online (Sandbox Code Playgroud)
有没有办法比较并获得正确的索引,而不是逐个检查每个字节?例如:
function GetArrayIndex(Source, Value: Array of Byte): Integer;
begin
..
end;
GetArrayIndex(A, B); // results 3
GetArrayIndex(A, C); // results -1
Run Code Online (Sandbox Code Playgroud)
先感谢您.
bum*_*mmi 12
function ByteArrayPos(const SearchArr : array of byte; const CompArr : array of byte) : integer;
// result=Position or -1 if not found
var
Comp,Search : AnsiString;
begin
SetString(Comp, PAnsiChar(@CompArr[0]), Length(CompArr));
SetString(Search, PAnsiChar(@SearchArr[0]), Length(SearchArr));
Result := Pos(Search,Comp) - 1;
end;
Run Code Online (Sandbox Code Playgroud)
这是Andreas 在这里重新编写的版本.
function BytePos(const Pattern: array of byte; const Buffer : array of byte): Integer;
var
PatternLength,BufLength: cardinal;
i,j: cardinal;
OK: boolean;
begin
Result := -1;
PatternLength := Length(Pattern);
BufLength := Length(Buffer);
if (PatternLength > BufLength) then
Exit;
if (PatternLength = 0) then
Exit;
for i := 0 to BufLength - PatternLength do
if Buffer[i] = Pattern[0] then
begin
OK := true;
for j := 1 to PatternLength - 1 do
if Buffer[i + j] <> Pattern[j] then
begin
OK := false;
Break;
end;
if OK then
Exit(i);
end;
end;
begin
WriteLn(BytePos(B,A)); // 3
WriteLn(BytePos(C,A)); // -1
ReadLn;
end.
Run Code Online (Sandbox Code Playgroud)
不过,Bummis的回答是喜欢的.好多了.
只是评论中提到的一句话.
对于小型数据集而言BytePos表现优异ByteArrayPos,而对于大型数据集(10000个项目),性能则相反.
这适用于32位模式,其中汇编程序优化的Pos()系统函数最适合大型数据集.
但是在64位模式下,没有汇编程序优化的Pos()函数.在我的基准测试中,对于所有类型的数据集大小,BytePos快4-6倍ByteArrayPos.
更新
基准测试是用XE3完成的.
在测试期间,我
purepascal在System.pas函数中发现了一个有缺陷的循环Pos().
添加了一个改进请求,QC111103,其中建议的功能大约快3倍.
我也对上面BytePos的内容进行了优化,并在下面作为ByteposEx().
function BytePosEx(const Pattern,Buffer : array of byte; offset : Integer = 0): Integer;
var
LoopMax : Integer;
OK : Boolean;
patternP : PByte;
patStart : Byte;
i,j : NativeUInt;
begin
LoopMax := High(Buffer) - High(Pattern);
if (offset <= LoopMax) and
(High(Pattern) >= 0) and
(offset >= 0) then
begin
patternP := @Pattern[0];
patStart := patternP^;
for i := NativeUInt(@Buffer[offset]) to NativeUInt(@Buffer[LoopMax]) do
begin
if (PByte(i)^ = patStart) then
begin
OK := true;
for j := 1 to High(Pattern) do
if (PByte(i+j)^ <> patternP[j]) then
begin
OK := false;
Break;
end;
if OK then
Exit(i-NativeUInt(@Buffer[0]));
end;
end;
end;
Result := -1;
end;
Run Code Online (Sandbox Code Playgroud)