Delphi中TList类应用
2015-06-02 10:18
477 查看
在DELPHI中指针最常见的就是和类TLIST结合起来使用。下面是一个很简单的例子,希望对这个例子的分析能让大家对使用TLIST类有一个简单的认识。 代码的功能是使用指针和Tlist来生成一个牌串,并将牌串保存在t_CardInfo中。 procedure TForm1.Button1Click(Sender: TObject); const //黑桃,红桃,方块,草花 CardType:array[0..3] of String = ('S','H','D','C'); const //取出的牌数 CardNums = 4; type //保存牌的指针信息 RCardrecord = record CardInfo:String[2]; end; PCard = ^RCardrecord; var t_List:TList; I:Integer; t_Sub,t_Spare:Integer; t_CardType,t_CardNum:String; p_Card:PCard; t_Random:Integer; t_CardInfo:String[8]; Count:Integer; begin //定义一个链表 t_List:=TList.Create; //使用循环将52张牌放入链表中 for I:=1 to 52 do begin t_Sub:=I div 14; t_Spare:=I mod 14; t_CardType:=CardType[t_Sub]; t_CardNum:=IntToHex(t_Spare,1); New(p_Card); p_Card.CardInfo:=t_CardType+t_CardNum; t_List.Add(p_Card); end; //使用随机从52张牌中抽取4张牌,并保存在 t_CardInfo中 Randomize; for I:=1 to CardNums do begin t_Random:=Random(t_List.Count); p_Card:=t_List.Items[t_Random]; t_CardInfo:=t_CardInfo+p_Card^.CardInfo; t_List.Delete(t_Random); DisPose(p_Card); end; //清空链表中的指针 Count:=t_List.Count; for I:=Count-1 downto 0 do begin p_Card:=t_List.Items[I]; t_List.Delete(I); DisPose(p_Card); end; //释放链表 t_List.Free; end; 分析: 1:我们首先创建一个Tlist类的对象t_List。 2:将52张牌按照相应的格式保存在这个t_List中。注意,这里t_List中保存的是每个牌的指针。 3:随机从这个链表中取出4个指针,并将指针对应的牌信息保存在变量t_CardInfo。因为在将指针插入到t_List中的时候,我们使用了New函数来申请内存,所以当从链表中删除这个指针的时候,一定要使用Dispose函数来释放,否则会形成内存泄露。 4:将t_List中剩余的指针释放。 5:释放对象t_List对象。
相关文章推荐
- delphi ocx在IE8下调试不能断点的问题
- Delphi 2007 一段代码手工折叠
- 使用Delphi实现JNI - 实例
- Delphi TcxComboBox控件说明
- 在delphixe7 编写dll中发现的问题s
- 使用Delphi实现JNI - 3
- 使用Delphi实现JNI - 2
- Delphi编译选项
- Delphi 快捷键
- Delphi webservices 传数据
- Delphi TClientDataSet的使用
- Delphi 复习代码
- 使用Delphi实现JNI - 1
- delphi TByteArray 装换成base64
- delphi excel 读取和写入
- Delphi常用快捷键
- DELPHI-Delphi常用类型及定义单元
- DELPHI XE7,开发代号Carpathia,一些新语法和新特性!
- Delphi读取Android设备联系人.DelphiXE6中编译通过
- C# VC VB Delphi Lazarus C++ builder 多种编程语言执行效率比较