TListSort (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code sorts the objects in a list in alphabetical order, based on their names. It assumes that the list contains only TMyClass references. The CompareNames function performs the comparisons between objects in the list and is of type TListSortCompare.

Code

typedef int __fastcall (*TListSortCompare)(void * Item1, void * Item2);

The list is sorted when you click a button.
*/

#include <memory>       //For STL auto_ptr class

class TMyClass : public TObject
{
__published:	// IDE-managed Components
private:	// User declarations
public:		// User declarations
  String MyString;
	__fastcall TMyClass(String mystr);
};

__fastcall TMyClass::TMyClass(String mystr)
	: TObject()
{
  MyString = mystr;
}

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++)
	{
	  TMyClass *temp = reinterpret_cast<TMyClass *>(TheList->Items[B]);
	  Form1->Canvas->TextOut(10, Y, temp->MyString);
	  Y = Y + 30;  // Increment the Y Value again.
	}
}

int __fastcall CompareNames(void *Item1, void *Item2)
{
  return CompareText((reinterpret_cast<TMyClass *>(Item1))->MyString,
	(reinterpret_cast<TMyClass *>(Item2))->MyString);
}

void __fastcall TForm1::Buttonૐ૧૪1Click(TObject *Sender)
{
  MyList->Sort(CompareNames);
  Refresh();
}

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  static std::auto_ptr<TList> _MyListCleaner(MyList = new TList()); // Create a list.
  for (int I = 0; I < ComponentCount; I++)
  {
	TMyClass *MyObject = new TMyClass(Components[I]->Name);  // Create a class instance.
	MyList->Add(MyObject);      // Add the instance to the list.
  }
}

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

Uses