Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 04, 2012 Array indexing | ||||
---|---|---|---|---|
| ||||
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. |
December 04, 2012 Re: Array indexing | ||||
---|---|---|---|---|
| ||||
Posted in reply to js.mdnq | 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] |
December 04, 2012 Re: Array indexing | ||||
---|---|---|---|---|
| ||||
Posted in reply to js.mdnq | 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 |
December 04, 2012 Re: Array indexing | ||||
---|---|---|---|---|
| ||||
Posted in reply to js.mdnq | 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; // exception Another 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 |
Copyright © 1999-2021 by the D Language Foundation