Remove elements without losing capacity

Steven Schveighoffer schveiguy at gmail.com
Tue Oct 4 15:42:21 UTC 2022


On 10/4/22 11:22 AM, Riccardo M wrote:
> Is it possible to remove elements from a range without losing its capacity?
> ```
> void main()
> {
>      import std.algorithm.mutation : remove, SwapStrategy;
>      import std.stdio : writeln;
> 
>      int[] arr = [1, 2, 3, 2, 4, 2, 5, 2];
> 
>      assert(arr.length == 8);
>      assert(arr.capacity == 11);
> 
>      arr = arr.remove!(SwapStrategy.unstable)(0);
> 
>      assert(arr.length == 7);
>      assert(arr.capacity == 0);
> }
> ```
> 
> Here capacity goes to 0. I wish to prevent future reallocations.
> 
> This loses the reserved capacity as well:
> ```
> arr.length--
> ```

Yes, you use `assumeSafeAppend`:

```d
arr.length--;
arr.assumeSafeAppend;
assert(arr.capacity != 0);
```

Now, I want to clarify that you should only use this if you are sure you 
are done with the data you removed at the end, as it will get 
overwritten upon more appends to the array.

e.g.:

```d
auto arr = [1, 2, 3];
auto arr2 = arr;
arr.length--;
arr.assumeSafeAppend;
arr ~= 42;
assert(arr2[2] == 42); // overwritten!
```

This leads to undefined behavior if the array is immutable (e.g. a string).

-Steve


More information about the Digitalmars-d-learn mailing list