Checking all elements are unique.
Edwin van Leeuwen via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Aug 31 01:31:19 PDT 2016
On Wednesday, 31 August 2016 at 07:40:39 UTC, Dorian Haglund
wrote:
> Hello,
>
> I have an array of objects of class C which contain a id member.
> I want to figure out if all the id members are unique using
> functional primitives.
>
> For example, if I have:
>
> class C
> {
> int id;
> }
>
> and an array of C 'Cs';
>
> My idea was to do:
>
> auto ids = Cs.map!(c => c.id);
> assert(equal(ids.sort().uniq(), ids.sort()));
>
> But it doesn't compile because I can't can call sort on ids.
>
> Any idea why ? and how to solve my initial problem, which is to
> check all ids are unique.
>
> Regards,
>
> Dorian
Sort require an indexable array. You can convert an insertRange
to an indexable array with .array:
ids.array.sort()
You can also directly sort on id
Cs.array.sort!((a,b) => a.id < b.id);
More information about the Digitalmars-d-learn
mailing list