Reputation: 3
This is the first time I use AddObject
method in C++ Builder 6 in a TStringList
but I can not add an integer to the object list for example. Of course I did it by means of casting different types. But it's not what I want. Please help me do it simpler
and why the objects must be Tobject*
in object list
this is my simple program...
#include <vcl.h>
#include <iostream.h>
#include <conio.h>
#pragma hdrstop
#pragma argsused
int main(int argc, char* argv[])
{
int r=random(100+1);
TStringList *mylist=new TStringList;
mylist->AddObject("r",(TObject *)r);
int i=mylist->IndexOf("r");
int a=(int)(mylist->Objects[i]);
cout<<a<<endl;
getch();
return 0;
}
Upvotes: 0
Views: 2687
Reputation: 596256
Use a std::map
or other suitable container instead, eg:
#pragma hdrstop
#include <iostream.h>
#include <conio.h>
#include <map>
#pragma argsused
int main(int argc, char* argv[])
{
int r = random(100+1);
std::map<std::string, int> mylist;
mylist["r"] = r;
int a = mylist["r"];
cout << a << std::endl;
getch();
return 0;
}
Upvotes: 1
Reputation: 4812
It's very ugly but the cast will work fine. The pragmatic approach is to stick with that method if you must use TStringList.
If you wanted, you could add TObject derived wrappers that hold 'int's to another vector and use these pointers but it require more code to maintain that second list, is more prone to errors and a lot slower.
Alternatively new these wrappers and add them to the stringlist and then manage deletion of the objects manually. This is error prone.
The best approach may be to ditch TStringList if that is possible. Use a struct/class or a std::pair and std::vector or std::deque.
e.g.
typedef std::pair<AnsiString, int> MyValue;
typedef std::vector<MyValue> MyValueList;
MyValueList list;
list.push_back(MyValue("hello", 1));
AnsiString const& s = list[0].first;
int i = list[0].second;
Upvotes: 0
Reputation: 5054
why the objects must be Tobject*
Because of Borland's design of VCL.
mylist->AddObject("r",(TObject *)r);
Do not do this, because there's no guarantee that TStringList
wouldn't call some methods of TObject*
inside AddObject
. For example it can call objectName()
or incrementReference()
(I know, that there's no TStringList::incrementReference()
but it's just an example).
IMHO, all that you need is std::map:
#include <map>
int main()
{
int r=random(100+1);
std::map< AnsiString, int > myList;
myList[ "r" ] = r;
int a = myList[ "r" ];
}
Upvotes: 0