On Monday, 30 December 2013 at 18:19:54 UTC, Dfr wrote:
This simple example:

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

Gives me: core.exception.RangeError: Range violation

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";

Does it *need* to be an array for some reason?
If so, resize the array prior.

Something like:

    // index is the position you're changing
    // value is the value you're changing to
    if(a.length <= index) {
        a.length = index+1;
    }
    a[index] = value;

If you're just mapping integers to strings, then you're probably looking for an associative array:
http://dlang.org/hash-map.html

This is probably more like what you actually want:

    string[size_t] a;
    a[1] = "works fine";
    a[10] = "also works fine";



isn't this will be inefficient ?

Yes. Resizing the array many times is very inefficient. Either use an associative array or know ahead of time what your array's length needs to be (or, at least, what it will "likely" need to be).

Reply via email to