www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - clear all elements from an array or AA ?

reply Sai <Sai_member pathlink.com> writes:
Hello all,

Is there any easy way to clear all elements from an array or AA ?

For array, will this work ? is this efficient ?
array.length = 0 

And how to clear an AA with out using for loop ?

Thanks
Sai
Aug 20 2004
next sibling parent J C Calvarese <jcc7 cox.net> writes:
In article <cg5hqv$kqr$1 digitaldaemon.com>, Sai says...
Hello all,

Is there any easy way to clear all elements from an array or AA ?

For array, will this work ? is this efficient ?
array.length = 0 

And how to clear an AA with out using for loop ?

Thanks
Sai

I thought there were three methods for clearing the items from an associative array, but I could only find two: 1. aA = null; /* implementation-dependent */ 2. foreach(char[] key; aA.keys) delete aA[key]; See http://www.dsource.org/tutorials/index.php?show_example=104 for more details. jcc7
Aug 20 2004
prev sibling parent "Ben Hinkle" <bhinkle mathworks.com> writes:
 Is there any easy way to clear all elements from an array or AA ?

 For array, will this work ? is this efficient ?
 array.length = 0

 And how to clear an AA with out using for loop ?

It depends :-) If you just want to clear the variable without regard to maintaining the capacity of the existing hash table, you can run array = array.init; Note if you had any other variables referring to the array data, like array2 = array; array = array.init; then array2 will not be affected. If you want to preserve the capacity of the hash table and simultaneously clear out the actual array contents so that all variables referring to the same array will be cleared, you'll need to use some compiler-dependent code. The following is copied from my MinTL library - you can use it however you like: /** Clear the contents of an associative array without losing * capacity. Compiler-dependent. * \param x the array to clear */ template reset(Key,Value) { void reset(Value[Key] x) { void*[] a = cast(void*[])x; a[] = null; } } For example: int[int] array; ... reset!(int,int)(array);
Aug 20 2004