Fastest way to "ignore" elements from array without removal

Steven Schveighoffer schveiguy at gmail.com
Tue Feb 16 15:27:09 UTC 2021


On 2/16/21 1:03 AM, H. S. Teoh wrote:
> For the former, you can use the read-head/write-head algorithm: keep two
> indices as you iterate over the array, say i and j: i is for reading
> (incremented every iteration) and j is for writing (not incremented if
> array[i] is to be deleted).  Each iteration, if j < i, copy array[i] to
> array[j].  At the end of the loop, assign the value of j to the length
> of the array.

std.algorithm.mutation.remove does this for you.

It's just a bit awkward as it doesn't do this based on values, you have 
to pass a lambda.

auto removed = arr.remove!(v => v == target); // removed is now the 
truncated array

And if you don't care about preserving the order, it can be done faster:

auto removed = arr.remove!(v => v == target, SwapStrategy.unstable);

-Steve


More information about the Digitalmars-d-learn mailing list