TListPack (C++)

From Appmethod Code Examples
Jump to: navigation, search

Description

This example requires two edit box controls and a button on the form. The code creates a list object and adds some strings to it. The fourth string in the list is a null string. The code counts the number of strings in the list and displays the number in the Edit1 control. The code then packs the list, removing the nil string, and counts the strings in the list again. The second count displays in the Edit2 control.


Code

#include <memory>       //For STL auto_ptr class
TList *MyList;

void __fastcall  DisplayTList(TList *TheList)
{
	// Now paint the items onto the paintbox. }
	short Y = 10;             // Variable used in TextOut function
	for (byte B = 0; B < TheList->Count; B++)
	{
	  String str = PChar(TheList->Items[B]);
	  Form1->Canvas->TextOut(10, Y, str);
	  Y = Y + 30;  // Increment the Y Value again.
	}
}

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  static std::auto_ptr<TList> _MyListCleaner ((MyList = new TList()));
  MyList->Add(PChar(L"A string")); // Add a string.
  MyList->Add(PChar(L"")); // Add an empty string.
  MyList->Add(PChar(L"A third string")); // Add a string.
  MyList->Add(NULL);              // Add nil.
  MyList->Add(PChar(L"A fifth string")); // Add a string.
  MyList->Add(PChar(L"")); // Add another empty string.
  MyList->Add(PChar(L"A seventh string")); // Add a string.
  Edit1->Text = IntToStr(MyList->Count); // Put count into Edit1.
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  MyList->Pack();                         // Pack the list.
  Edit2->Text = IntToStr(MyList->Count); // Put count into Edit2.
  Repaint();
}

void __fastcall TForm1::FormPaint(TObject *Sender)
{
  DisplayTList(MyList);
}

Uses