Dfr:

string[] a;
a[10] = "hello";

Gives me: core.exception.RangeError: Range violation

Because 'a' has length 0, so the position with index 11 doesn't exists in the array.

By the way, this is not an "appending", it's a (failed) assignment.


I know about this way:

string[] a;
a = new string[11];
a[10] = "hello";

But what if i need do this many times with the same array like this:

a[10] = "a";
...
a[1] = "b";
..
a[1000] = "c";

If i will call "a = new string[11]" all those many times, isn't this will be inefficient ? Also it will clear all previous contents of "a", which is not suitable.

If you need to assign strings randomly then a good solution is to use an associative array, that is a quite different data structure:

string[int] aa;
aa[10] = "a";
aa[1] = "b";
aa[1000] = "c";


As alternative if you want a normal dynamic array, you can resize it:

string[int] a;
a.length = max(a.length, 10 + 1);
a[10] = "a";
a.length = max(a.length, 1 + 1);
a[1] = "b";
a.length = max(a.length, 1000 + 1);
a[1000] = "c";

Bye,
bearophile

Reply via email to