Original Post
🔒 Locked
Array redimension
Advertisement
C++''s standard vector class is great. I would also recommend using it unless you want to learn how to do this yourself. To redimension an array, you want to do something like this:
#include <algorithm>
using std::copy;
using std::swap;
int main()
{
// p refers to the array that is to be resized
int* p = new int[old_size];
// redimension p to the new size while preserving old values
int* temp = new int[new_size]; // allocate new space
copy(p, p+old_size, temp); // copy old elements over (optional)
swap(p, temp); // swap the pointers, now p refers to the new array
delete [] temp; // deallocate old array
// at some point, we need to deallocate memory for the array
delete [] p;
return 0;
}
Remember that the example I gave you assumes that "new_size" is greater than or equal to "old_size." To wrap this code up into a function we do:
Edited by - null_pointer on December 31, 2001 3:01:40 PM
|
Edited by - null_pointer on December 31, 2001 3:01:40 PM
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement