[phobos] array.shift for deletion/insertion
spir
denis.spir at gmail.com
Fri Feb 25 15:08:17 PST 2011
Hello,
There is no builtin func to delete or insert one or more elements from or into
a dynamic array. The reason is probably that providing a dedicated idiom may
let such an operation look cheap (same reason as for refusing 'in' for dyn arrays).
Still, there is a need for this functionality, to avoid
* either repetedly coding it when needed, possibly with bugs,
* or using concat, which copies the whole content instead of the necessary part.
For both operations, the actual process is a shift operation on the part of the
array ranging from a lower bound to the upper end, for an offset equal to the
deleted/inserted slice's length. We could, I guess, provide this shift process
builtin. This would allow writing deletion/insertion easily, while making it
obvious that the operation is costly.
See example below. What do you think?
Denis
void shift (T) (ref T[] array, size_t low, sizediff_t offset) {
if (offset == 0) return;
auto len = array.length;
size_t i;
// move up for insertion: proceed backwards
if (offset > 0) {
array.length = len + offset;
for (i=len-1 ; i>=low ; i--)
array[i+offset] = array[i];
}
// move down for deletion: note offset is negative!
else {
for (i=low ; i<array.length ; i++)
array[i+offset] = array[i];
array.length = len + offset;
}
}
unittest {
auto a = [0,1,2,3,4,5,6,7,8,9];
writeln(a);
// delete [4..6]
a.shift(7, -3);
writeln(a); // [0,1,2,3,7,8,9]
// insert [4..6]
a.shift(4, +3);
a[4..7] = [4,5,6];
writeln(a); // [0,1,2,3,4,5,6,7,8,9]
}
--
_________________
vita es estrany
spir.wikidot.com
More information about the phobos
mailing list