remove element from dyn array by element, (not by index)
bearophile
bearophileHUGS at lycos.com
Tue Jan 15 04:35:03 PST 2008
This may help clear your mind some:
import std.stdio: writefln;
import std.string: format;
void removeBang(T)(ref T[] arr, T el) {
foreach(i, x; arr)
if (x == el) {
arr = arr[0 .. i] ~ arr[i+1 .. $];
break;
}
}
class C(bool withEqual) {
int x;
this(int x) {
this.x = x;
}
string toString() {
return format("C(%d)", x);
}
static if (withEqual) {
bool opEquals(C other) {
return this.x == other.x;
}
}
}
void main() {
int[] a = [1, 2, 3, 4, 1];
writefln(a);
a.removeBang(4);
writefln(a);
writefln;
alias C!(true) C1;
auto b = new C1(2);
C1[] oa = [new C1(1), b, new C1(3)];
removeBang(oa, b);
writefln(oa);
removeBang(oa, new C1(1));
writefln(oa);
writefln;
alias C!(false) C2;
auto b2 = new C2(2);
C2[] oa2 = [new C2(1), b2, new C2(3)];
removeBang(oa2, b2);
writefln(oa2);
removeBang(oa2, new C2(1));
writefln(oa2);
}
Output:
[1,2,3,4,1]
[1,2,3,1]
[C(1),C(3)]
[C(3)]
[C(1),C(3)]
[C(1),C(3)]
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list