TListIndexOf (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code adds an object to MyList if it is not already in the list.


Code

#include <memory>       //For STL auto_ptr class

typedef struct AList
{
  int I;
  char C;
} TAList;

typedef AList* PAList;

TList *MyList;
PAList ARecord1, ARecord2;

void __fastcall DisplayTList(TList *theList)
{
  PAList AStruct;
  // Go through the list, writing the elements 
  // to the canvas of a paintbox component.
  int Y = 10; // Position on canvas
  for (int i = 0; i < theList->Count; i++)
  {
	AStruct = (PAList) theList->Items[i];
	Form1->PaintBox1->Canvas->TextOut(10, Y, IntToStr(AStruct->I));
	Y += 30;  // Increment the Y Value.
	Form1->PaintBox1->Canvas->TextOut(10, Y, AStruct->C);
	Y += 30;  //Increment the Y Value again.
  }
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  if (MyList->IndexOf(ARecord1) == -1) MyList->Add(ARecord1);
  DisplayTList(MyList);
}

void __fastcall TForm1::Button2Click(TObject *Sender)
{
  if (MyList->IndexOf(ARecord2) == -1) MyList->Add(ARecord2);
  DisplayTList(MyList);
}

void __fastcall TForm1::Button3Click(TObject *Sender)
{
  if (MyList->Count != 0)
  {
	for (int B = MyList->Count - 1; B >= 0; B--)
	{
	  PAList ARecord;
	  ARecord = PAList(MyList->Items[B]);
	  MyList->Remove(ARecord);
	}
  }
  Form1->PaintBox1->Repaint();
}

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  static std::auto_ptr<TList> _MyListCleaner(MyList = new TList);
  static std::auto_ptr<TAList> _ARecord1Cleaner(ARecord1 = new TAList);
  ARecord1->I = 100;
  ARecord1->C = 'Z';
  static std::auto_ptr<TAList> _ARecord2Cleaner(ARecord2 = new TAList);
  ARecord2->I = 200;
  ARecord2->C = 'X';
}

Uses