Reputation: 121
I allocate memory like this:
int *array = new int[n];
array[5] = 3;
and then assign values to it. However, I would like to free some space allocated by it in the meantime. I know that
delete[]
will deallocate the memory used by it, but I don't want the whole array deleted, but only certain elements, such as the first one, in order to implement a FIFO list. How can I deallocate the first element and then allocate space for a new element at the end of the array without deleting the whole thing? Can it be done with vectors instead of int?
Upvotes: 1
Views: 1590
Reputation: 2095
first
and last
, write new elements to array[last % RingBufferSize]
followed by increment of last
and read elements from array[first % RingBufferSize]
followed by increment of first; when first == last
it means that your FIFO is empty, when (first + 1) % RingBufferSize == last % RingBufferSize
it means that your FIFO is full and you can't add without rejecting oldest item. With this approach you can use a static array and completely avoid using heap traffic.log(N)
for addition and removal, which is much better than O(N)
patching the hole in your array by copying it in a new array without an element being removed.Upvotes: 0
Reputation: 7128
Once allocated, you can deallocate the memory in its entirety. Partial deallcoation is not possible. However, you may re-allocate another space with desired number of elements and then copy the earlier content to newly allocated ones and deallocate the earlier one. For example,
int *array = new int[n];
array[5] = 3;
std::vector<int> myvec(n1); // n1 is the new size
std::copy (array, array+std::min(n1,n), myvec.begin() );
delete [] array;
Upvotes: 1