Associative array literal: length wrong when duplicate keys found
Ivan Kazmenko via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jan 31 11:45:33 PST 2017
On Tuesday, 31 January 2017 at 17:20:00 UTC, John Colvin wrote:
> It's a bug, please report it. The initializer should be
> statically disallowed.
>
> Adding a .dup works around the problem.
OK. Hmm, but the real use case was a bit more complicated, more
like:
-----
int n = 10;
foreach (i; 0..n)
foreach (j; 0..n)
foreach (k; 0..n)
... and maybe a couple more ...
if ([i: true, j: true, k: true].length == 3)
{...} // i, j, k is a set of distinct values
-----
Here, we don't know i, j and k statically, yet the problem is the
same.
Anyway, I'll file a bug report.
> By the way, you can do sets like this, avoiding storing any
> dummy values, only keys:
>
> struct Set(T)
> {
> void[0][T] data;
>
> void insert(T x)
> {
> data[x] = (void[0]).init;
> }
>
> void remove(T x)
> {
> data.remove(x);
> }
>
> bool opBinaryRight(string op : "in")(T e)
> {
> return !!(e in data);
> }
>
> // other things like length, etc.
> }
>
> unittest
> {
> Set!int s;
> s.insert(4);
> assert(4 in s);
> s.remove(4);
> assert(4 !in s);
> }
Yeah, thanks for the recipe! I usually do bool [key] since it
does not add much overhead, but would definitely like the real
set (void[0] or otherwise) when performance matters.
Ivan Kazmenko.
More information about the Digitalmars-d-learn
mailing list