Lois2B
Lois2B

Reputation: 121

How do I deallocate a single element of an array?

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

Answers (2)

Minor Threat
Minor Threat

Reputation: 2095

  1. You can implement FIFO by using a ring buffer: just introduce two variables: 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.
  2. Use binary heap with keys taken from addition order (oldest first). With this approach, you'll have to grow allocated memory for your array only when it's getting overflown (that means "never" if your data source and data sink are working with the same speed and you need queue to damper the data stream). The binary heap itself has complexity about 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

Dr. Debasish Jana
Dr. Debasish Jana

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

Related Questions