I am doing this learning/practicing with arrays of objects and array of pointers to objects and I’m very confused about how to get dynamic arrays sizes.
I’ve got this:
private:
Client ** arr_client;
public:
static string members [];
then populated the array arr_client with tokenized data from the following static string array members:
static string members[] = {"Jhon Perez 623 22 12 1998"
,"Louis Smith 199 02 12 1988"
,"Daniel Martinez 106 02 01 2010"};
void load(void){
arr_client = new Client * [(sizeof(members)/sizeof(string))*sizeof(Client)];
for (i = 0; i < (sizeof(members)/sizeof(string)); i++){
istringstream stream(members[i],ios_base::in);
stream >> name;
stream >> lastname;
stream >> aux;
id = atoi(aux.c_str());
stream >> date;
date.append(" ");
stream >> aux;
date.append(aux);
date.append(" ");
stream >> aux;
date.append(aux);
arr_client[i] = new Client(name,lastname,id,date);
}
}
now, after the object array is full, I want to loop through arr_client but I cant seem to find the way to do it.
should I use:
for (int i =0; i < (sizeof(**arr_client)/sizeof(client)); i++)
or take the previous cal for size and do:
for (int i =0; i < (sizeof(members)/sizeof(string)); i++)
and be done with it? doesn’t look that usefull to me… but then again I’m very new.
Few questions I’ve also got:
What if I don’t know the size of that dynamically assinged array of objects? like in this case that im building upon a known sized array.
How can count how many elements are in it so I could loop through it?
Could I use an std::iterator for arr_client?
Any tips would be much appreciated =)
and…. yes, I do know about <vector> and it’s advantages but never hurts to know about these scenarios.
First, I applaud you for trying to learn the fundamentals before adopting an advanced tool like
vector.There’s no clean and reliable way to do what you ask. People usually remember the size of an array in a separate variable, like this:
If you really want to determine the size of an array at runtime, you can do it with a template: