//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "TListSort.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
TList *MyList;

 //---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
// BeginExample: TListSort
// Method: Classes.TList.Sort
// Type: Classes.TListSortCompare


// BeginCode
/*
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:

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

The list is sorted when the user clicks a button.
*/

#include <memory>       //for STL auto_ptr class

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

__fastcall TMyClass::TMyClass(AnsiString 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 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::Button1Click(TObject *Sender)
{
  MyList->Sort(CompareNames);
  Refresh();
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  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 instance to list
  }
}

void __fastcall TForm1::FormPaint(TObject *Sender)
{
  DisplayTList(MyList);
}
// EndCode
// EndExample: TListSort
//---------------------------------------------------------------------------

void __fastcall TForm1::FormDestroy(TObject *Sender)
{
	for (int B = 0; B < MyList->Count; B++)
	{
	  TMyClass *Temp = reinterpret_cast<TMyClass *>(MyList->Items[B]);
	  delete Temp;
	}
}
//---------------------------------------------------------------------------

