remove

Remove all elements matching predicate.

@safe @trusted
@"complexity", "O(length)"
size_t
remove
(
alias predicate
C
)
(
ref C c
)
if (
isInstanceOf!(DynamicArray, C) &&
is(typeof(unaryFun!predicate(C.init[0])))
)

Return Value

Type: size_t

number of elements that were removed.

TODO implement version that doesn't use a temporary array tmp, which is probably faster for small arrays.

Examples

construct and append from slices

alias T = int;
alias A = DynamicArray!(T, null, uint);
static if (size_t.sizeof == 8) // only 64-bit
    static assert(A.sizeof == 2 * size_t.sizeof); // only two words

auto a = A([10, 11, 12].s);

a ~= a[];
assert(a[] == [10, 11, 12,
               10, 11, 12].s);

a ~= false;
assert(a[] == [10, 11, 12,
               10, 11, 12, 0].s);
alias T = int;
alias A = DynamicArray!(T);

A a;

a.length = 1;
assert(a.length == 1);
assert(a.capacity >= 1);

a[0] = 10;

a.insertBack(11, 12);

a ~= T.init;
a.insertBack([3].s);
assert(a[] == [10, 11, 12, 0, 3].s);

import std.algorithm.iteration : filter;

a.insertBack([42].s[].filter!(_ => _ is 42));
assert(a[] == [10, 11, 12, 0, 3, 42].s);

a.insertBack([42].s[].filter!(_ => _ !is 42));
assert(a[] == [10, 11, 12, 0, 3, 42].s);

a ~= a[];
assert(a[] == [10, 11, 12, 0, 3, 42,
               10, 11, 12, 0, 3, 42].s);
alias T = int;
alias A = DynamicArray!(T);

A a;                        // default construction allowed
assert(a.empty);
assert(a.length == 0);
assert(a.capacity == 0);
assert(a[] == []);

auto b = DynamicArray!int.withLength(3);
assert(!b.empty);
assert(b.length == 3);
assert(b.capacity == 3);
b[0] = 1;
b[1] = 2;
b[2] = 3;
assert(b[] == [1, 2, 3].s);

b[] = [4, 5, 6].s;
assert(b[] == [4, 5, 6].s);

const c = DynamicArray!int.withCapacity(3);
assert(c.empty);
assert(c.capacity == 3);
assert(c[] == []);

// TODO this should fail with -dip1000
auto f() @safe
{
    A a;
    return a[];
}
auto d = f();

const e = DynamicArray!int([1, 2, 3, 4].s);
assert(e.length == 4);
assert(e[] == [1, 2, 3, 4].s);
alias T = int;
alias A = DynamicArray!(T);

auto a = A([1, 2, 3].s);
A b = a.dup;                // copy construction enabled

assert(a[] == b[]);          // same content
assert(&a[0] !is &b[0]); // but not the same

assert(b[] == [1, 2, 3].s);
assert(b.length == 3);

b ~= 4;
assert(a != b);
a.clear();
assert(a != b);
b.clear();
assert(a == b);

auto c = A([1, 2, 3].s);

DIP-1000 return ref escape analysis

alias T = int;
alias A = DynamicArray!T;

T[] leakSlice() @safe pure nothrow @nogc
{
    A a;
    return a[];             // TODO shouldn't compile with -dip1000
}

T* leakPointer() @safe pure nothrow @nogc
{
    A a;
    return a._store.ptr;    // TODO shouldn't compile with -dip1000
}

auto lp = leakPointer();    // TODO shouldn't compile with -dip1000
auto ls = leakSlice();      // TODO shouldn't compile with -dip1000

Meta