Inability to dup/~ for const arrays of class objects

Peter Williams pwil3058 at bigpond.net.au
Mon Jun 3 22:25:09 PDT 2013


On 04/06/13 11:56, Steven Schveighoffer wrote:
> On Mon, 03 Jun 2013 20:06:14 -0400, Peter Williams
> <pwil3058 at bigpond.net.au> wrote:
>> I use a = a[0..i] ~ v ~ a[i..$] for insertion into a sorted array as
>> I'm willing to pay the cost of allocation for the convenience of array
>> notation.  One advantage is that finding i is O(log(a.length)) instead
>> of O(a.length()).  I also reasoned that the compiler can use memcopy()
>> (or whatever its name is) to do the reallocation and therefore it
>> should be fairly quick.
>
> ugh.  Sorry, the performance miser in me must object :)

I worry about correct first and then come back and worry about 
efficiency.  That way I have tests in place to make sure I don't break 
things during tweaking.  :-)

>
> There are better ways to do this, using range operations.  I'm pretty
> sure you could do it with std.algorithm.copy.

To insert "newElement" into array a" at index "i" where "i <= a.length", 
I've come up with:

     a ~= newElement;
     if (a.length > 1 && i < a.length - 1) {
         copy(retro(a[i .. $ - 1]), retro(a[i + 1 .. $]));
         a[i] = newElement;
     }

which works (i.e. it is correct in that it passes my unit tests).  I'm 
assuming allocation will only occur if it's required for the first line?

Peter
PS It's not as pretty as the original.
PPS For remove, "a = a.remove(index);" does the job.



More information about the Digitalmars-d mailing list