Hi, is this an unsafe way of being able to make a variable number of variables? I don't want to have to declare everything beforehand since there would be many variables and I'd like to be able to create and delete them based on user actions, but is it unsafe to do what I do below, using the same name for each new member and all? The test program I wrote appears to work though. Is there a better way of doing this?
Thanks
I was using pointers because I wanted to be able to have a list of variables, which could be shortened or made longer based on user input, and i thought a vector of pointers would allow that. Else I thought i would have to have a long array pre-made, and i would have to put elements of that array into the vector when the user performs an action, and I tried that at first but the code got more complicated than I was hoping, and so I wanted to try something else.
I believe if I remove the asterisk on line ten I would be creating a vector of integers, rather than pointers to integers, and so I would have to adjust the rest of the code accordingly. Except can't you only use 'new' to create pointers?
Is there a better way of accomplishing this in-process declaration of variables, or should I just use a long pre-defined array?
Let me know if I'm not making sense.
Thanks
I second L B's mentioning of std::vector. For the majority of cases that I've needed a dynamic array, vector has suited me just fine. (I've had some exceptions but few).
Vectors make anything from staying in bounds to memory management easier to do.
but.. I thought you could only add an element to a vector if the element existed already.
Like in order to have a vector of two integers you'd have to say
1 2 3 4 5
int x;
int y;
vector<int> vec1;
vec1.push_back(x);
vec1.push_back(y);
Can you make a vector without first having the elements exist elsewhere?
Or to refine that.. I just would rather not have to first declare a long list of variable and then add/subtract them into the vector whenever the user performs a command, but would my initial code be safe if I just didn't use pointers? As in, I initialize a temporary variable and add that to the vector, and then reuse the temporary variable again later to add another element to the vector? I feel like that shouldn't be ok though.
So either, can you reuse a variable to add elements to a vector, or is there a way to lengthen a vector without using push_back?
No, you don't need that function at all. push_back resizes the vector for you. How could you think that a vector of pointers was any different from a vector of non-pointers? ;)