Arrays are sufficient for ArrayLists? Really??

Jonathan M Davis jmdavisProg at gmx.com
Mon May 16 12:37:42 PDT 2011


On 2011-05-16 12:26, Mehrdad wrote:
> On 5/16/2011 12:25 PM, Timon Gehr wrote:
> > Mehrdad wrote:
> >> Timon:
> >>> What about:
> >> void removeAt(T)(ref T[] arr, size_t index)
> >> {
> >> 
> >>     foreach (i, ref item; arr[1 .. index+1])
> >>     
> >>          item = arr[i - 1];
> >>      
> >>      arr = arr[1 .. $]; //note how no valid data is beyond the end of
> >>      the array
> >> 
> >> }
> >> 
> >> Clever, but if you do this with a big enough number of items, you'll
> >> exhaust all memory. Be careful. :P
> > 
> > Total memory usage is at most 2 times the maximum size the array reaches
> > during its lifetime. Test it.
> 
> Whoops, my bad, I was under the impression that the array could
> potentially grow forever if I added elements, which obviously isn't
> true... yeah, seems like this would work too, interesting! I'll
> definitely test it, thanks!

It'll grow, but if it doesn't have enough space to grow, it has to reallocate, 
which means that any other slices/arrays which pointed to any portion of that 
array will not point to the new array. And you obviously can't have an array 
bigger than the amount of memory that you have, so you definitely can't make 
it grow forever. But it would be incredibly rare to have an application which 
needed an array larger than you could make.

- Jonathan M Davis


More information about the Digitalmars-d mailing list