Consider the following:
Now suppose we want to add a 6th element (without using vector)Code:int *p; p = new int[5]; for(int i=0;i<5;i++) *(p+i)=i;
One way is to copy it across to a larger array:
This looks like a very expensive operation and im looking for other ways.Code:int *p; p = new int[5]; for(int i=0;i<5;i++) *(p+i)=i; // realloc int* temp = new int[6]; std::copy(p, p + 5, temp); delete [] p; p = temp;
Three questions regarding the above:
- Not using vector, is this the best way to do this?
- What about using realloc? How would I use realloc in this situation?
- Any other ways apart from realloc or vector?