std.algorithm.remove from array of custom classes?
BBaz via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Dec 9 05:13:36 PST 2015
On Wednesday, 9 December 2015 at 13:05:31 UTC, Tim K. wrote:
> Hi!
>
> I'm trying to remove an item from an array of objects. But I
> get error messages when compiling (see below) which I do not
> understand. I figured I had to override opEquals for it to
> work, but no.
> How do I get this to work?
You should read the documentation, there is two errors:
1) remove works with an index
2) remove does not remove in place
so with
~~~~~~~~~~~~~~~~~~~~~~~~~~
import std.stdio;
import std.algorithm;
class A
{
this(string si, uint ui) { s = si; u = ui; }
string s;
uint u;
override bool opEquals(Object obj) const
{
if (A o = cast(A)obj)
return (s == o.s) && (u == o.u);
else
return false;
}
}
void main(string[] argv)
{
A a = new A("a", 1);
A b = new A("b", 2);
A[] as = [a, b];
as = as.remove(0);
writeln(as);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~
also, off topic but 2 other advices/errors
3) opEquals can be 'const' because the method doesn't mutate the
state of the object
4) your cast wasn't safe
http://dlang.org/phobos/std_algorithm_mutation.html#.remove
More information about the Digitalmars-d-learn
mailing list