digitalmars.D.learn - Array indexing
- js.mdnq (13/13) Dec 03 2012 When accessing an element outside a dynamic array I get an
- Adam D. Ruppe (5/5) Dec 03 2012 Try
- bearophile (9/13) Dec 03 2012 D dynamic arrays don't expand themselves "on demand" on array
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (7/12) Dec 03 2012 Another option is to modify the length of the "slice" (yes, "slice", not...
When accessing an element outside a dynamic array I get an exception. I thought in D arrays will automatically expand themselves? If not, how do I add an element to an array? int[] arr = new int[1]; arr[1] = 34; // exception If I change this to int[] arr = new int[2]; arr[1] = 34; Then it works. (similar to C/C++) But my arrays will be growing and I do not know the final size ahead of time. arr.add(34) does not work.
Dec 03 2012
Try arr ~= 33; the ~= operator means append to. You can also do auto a = [1,2] ~ [3,4]; which would give [1,2,3,4]
Dec 03 2012
js.mdnq:When accessing an element outside a dynamic array I get an exception. I thought in D arrays will automatically expand themselves?D dynamic arrays don't expand themselves "on demand" on array access, it's not efficient (and I think it's not a very clean operation, despite some languages do it). On the other hand D associative arrays grow if you add them key-values.arr.add(34) does not work.To append to a dynamic array use: arr ~= 34; Bye, bearophile
Dec 03 2012
On 12/03/2012 04:43 PM, js.mdnq wrote:When accessing an element outside a dynamic array I get an exception. I thought in D arrays will automatically expand themselves? If not, how do I add an element to an array? int[] arr = new int[1]; arr[1] = 34; // exceptionAnother option is to modify the length of the "slice" (yes, "slice", not "array"): arr.length = 100; The following is almost mandatory reading: :) http://dlang.org/d-array-article.html Ali
Dec 03 2012