C++/A question about new operator
Expert: Eddie - 8/14/2004
QuestionDear Eddie,
Suppose that I define an array of a class in this way:
ClassName arr = new ClassName[100];
How can I extend the array length to 101?( Suppose that this array is a vector of attributes and I want to add a new attribute to the end of array using a function like 'addAttribute' in my class, How this function should be written? )
void addAttribute( ClassName newAttr )
{
???
}
Thank you in advance,
Sincerely,
Arash Afkanpour
AnswerHello Arash,
I'm so sorry it has taken so long to reply. I still have no power from hurricane Charley. It destroyed everything in Orlando.
Well, to answer your question:
int iSize = 100;
Class array[iSize] = new Class;
++iSize;
Class array1[iSize] = new Class;
memcpy(array1, array, sizeof(Class) * (iSize - 1));
delete [] array;
That would be the hack way of doing it. A better way is to use the STL vector class built into C++. It dynamically resizes itself based on size. The cool part about it is that you can index it like an array.
#include <vector>
using namespace std;
vector<int> vec;
// in a function
for(int i = 0; i < 1000; i++)
vect.push_back(i);
// in main
for(int i = 0; i < 1000; i++)
cout << vec[i] << '\n';
Sorry my reply could not be in more detail, I have sparse internet access.
I hope this helps,
- Eddie