The short answer is that what you're trying to do isn't possible.
You must first store the values you want to save and then delete the entire array.
Then you must create a new array and fill it with the values.
No way around this using simple heap memory operations like new and delete.
The reason for this is that heap memory is allocated in contigious blocks, so for obvious reasons, it may not be possible to *grow* the size of an array, therefore this is not permitted, and as a matter of consistency, they cannot be shrunk either.
Honestly, there is no practical reason to do what you're trying to do. It simply just isn't that crucial to delete just one (or a few) elements of heap memory. There is considerable overhead involved in memory allocation and memory freeing operations, so programmers try to avoid doing them frequently.
For instance, a common method for 'dynamic arrays' is to begin by making the array some reasonable initial size N. Then, whenever the array is filled, the array is destroyed and recreated with size 2*N. This process is repeated everytime the array needs to be grown. By this method, you balance the fact that a few extra bytes of memory is a minimal cost, whereas constantly burning CPU to perform slow operations such as memory management is a much greater cost. Waste more, run faster.
If you would like to do the most elegant design, I would recommend you just use a class that encapsulates 'array' functionality in a doubly (or singly) linked list. You would therefore overload the [] operator and other useful operators (for instance, + could be used for array concatenation) and you could manage the array in any way you wished. Of course then you would have the ability to grow or shrink the 'array', as well as delete an element at any arbitrary position, or add an element at any arbitrary position.
If you explore the usage of templates in C++, you can even make this class type-generic so that it could be used with INTs, FLOATs, or even structs or other objects.
__________________ Desktop machine: 2 x Opteron 246, Asus K8N-DL, 2GB PC3200 ECC Reg., XFX GeForce 6600GT, 74gb WD Raptor, 2 x 19\" LCDs, Windows XP x64
Server machine: Intel P4 3.0GHz 2MB EM64T, ECS i865pe, 1GB PC3200, 36gb WD Raptor, Windows Server 2003
Laptop: Dell Inspiron 9100 (Intel P4 3.2GHz 1MB Prescott, i865pe, 512MB PC3200, Mobility Radeon 9700, DVD+R/DL Burner), Windows XP
Linux: P3 450Mhz, 386MB ram, Slackware 10.1 (Running mySQL/Apache) |