zoukankan      html  css  js  c++  java
  • Delphi中TList类应用

    在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对象。
     
     
  • 相关阅读:
    [LeetCode] 75. 颜色分类(荷兰国旗)
    [LeetCode] 347. 前K个高频元素
    CMU-14445 数据库原理 汇总
    MIT-6.824 操作系统 汇总
    发布一个基于协程和事件循环的c++网络库
    记录一次gdb debug经历
    彻底弄懂UTF-8、Unicode、宽字符、locale
    CPU使用率原理及计算方式
    TCP使用注意事项总结
    STL-vector
  • 原文地址:https://www.cnblogs.com/easypass/p/1600813.html
Copyright © 2011-2022 走看看