Delphi中的THashTable
在Delphi中,Inifiles单元中有一个TStringHash的类,不过它的Value仅支持Integer(其实也不是问题,有其它类型可以将变量变为Pointer),有点不舒服,今天没事做就把它替换为variant了,其中Key的名称大小写无关,就是为了加快开发速度!
使用Hashtable,查找和删除复杂度都是常数级别的!
type
PPHashItem = ^PHashItem;
PHashItem = ^THashItem;
THashItem = record
Next: PHashItem;
Key: String;
Value: Variant;
end;
THashTable = class
private
Buckets: array of PHashItem;
protected
function Find(const Key: String): PPHashItem;
function HashOf(const Key: String): Cardinal; virtual;
public
constructor Create(Size: Cardinal = 256);
destructor Destroy; override;
procedure Put(const Key: String; Value: Variant);
procedure Clear;
procedure Remove(const Key: String);
function Modify(const Key: String; Value: Variant): Boolean;
function Get(const Key: String): Variant;
function ContainKey(const Key: String):boolean;
end;
procedure THashTable.Clear;
var
I: Integer;
P, N: PHashItem;
begin
for I := 0 to Length(Buckets) - 1 do
begin
P := Buckets[I];
while P <> nil do
begin
N := P^.Next;
Dispose(P);
P := N;
end;
Buckets[I] := nil;
end;
end;
function THashTable.ContainKey(const Key: String): boolean;
var
P: PHashItem;
begin
P := Find(Key)^;
if P <> nil then
begin
Result := True;
end
else
Result := False;
end;
constructor THashTable.Create(Size: Cardinal);
begin
inherited Create;
SetLength(Buckets, Size);
end;
destructor THashTable.Destroy;
begin
Clear;
inherited Destroy;
end;
function THashTable.Find(const Key: String): PPHashItem;
var
Hash: Integer;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
Result := @Buckets[Hash];
while Result^ <> nil do
begin
if Result^.Key = Key then
Exit
else
Result := @Result^.Next;
end;
end;
functio
相关文档:
var
arrChar : array [0..4] of Char;
b : Byte;
s : string;
begin
s := 'Test';
Move(Pointer(s)^, arrChar, Length(s)); //string to array of char
ShowMessage(arrChar);
b := Ord(s[1]); //First byte string to one single byte
......
使用delphi多年,前些天忽然遇到不会string转pbyte,很是失落,此时对于编程基本功的重要性深有体会.这其中用到MOVE函数.
搞了好一会才搞明白其用法.所以想贴出来帮助需要帮助的人.
var
s:string;
ps:Pchar;
b:pbyte;
len:integer;
begin
&nb ......
不论数组元素是什么类型,静态数组的局部变量总会在栈上分配。如果堆栈大小不够将会导致异常。下例暗藏着一个危险的bug
procedure stackover;
var
s:array [0..4100] of string[255];
begin
end;
delphi默认栈最大为$100000字节,上例中的栈上分配的大侠为256*4100>$10000。测试必然会出现异常Stack overf ......
在Delphi中Ado系列控件使用xxxxx.Parameters.Refresh,可以获得存储过程的Return值
以TADOStoredProc为例
ADOStoredProc1.Connection := 'xxxx';
ADOStoredProc1.ProcedureName := 'XXXX';
ADOStoredProc1.Parameters.Refresh; //刷新存储过程的参数列表
//参数赋值
ADO ......