Board index » cppbuilder » Dynamic alloc to an object

Dynamic alloc to an object

How do I do something like the following:

int i;

for(i = 0; i < 5 i++)
{
    TStrings    *sMyList + i = new TStringList();

Quote
}

So that I come up with 5 string lists like:

sMyList0
sMyList1
sMyList2
etc.

?

Thanks
Ted

 

Re:Dynamic alloc to an object


Quote
> int i;

> for(i = 0; i < 5 i++)
> {
>     TStrings    *sMyList + i = new TStringList();
> }

> So that I come up with 5 string lists like:

> sMyList0
> sMyList1
> sMyList2
> etc.

You need to do an array as :

TStringsList** MyList[10]; // for exemple

for(i = 0; i < 5; i++)
 {
     MyList[i]= new TStringList();
 }

and then you have
MyList[0], MyList[1], ... MyList[9].

You can use also a special means that it called vector.
If you don't know how many TStringList you want at
compile time or if this number can be decreased or
increased, you'd better use vector :

#include <vector>

std::vector<TStringList*> MyList;

MyList.push_back(new TStringList()); // add a TStringList
MyList.pop_back();// remove the last TStringList

access : MyList[0], .. MyList[n-1] where n is the number of TStringList

In all cases, don't forget to destroy the TStringList when you
don't have longer need of it (end of the prog for instance)
with delete MyList[i]; // i : 0 ->n-1 in a for loop

HTH

Re:Dynamic alloc to an object


Quote

> TStringsList** MyList[10]; // for exemple

correction : TStringList* MyList[10]; // for exemple

also it is TSringList and not TStringsList
I hope there is no more typos...

Other Threads