How to use sets in D?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Feb 7 22:03:00 UTC 2020


On Fri, Feb 07, 2020 at 07:37:08PM +0000, mark via Digitalmars-d-learn wrote:
> I am porting code from other languages to D as part of learning D, and
> I find I've used sets quite a lot. AFAIK D doesn't have a built-in set
> type or one in the std. lib.
> 
> However, I've been perfectly successfully using int[E] where E is my
> ElementType, and adding with set[element] = 0. I mostly only need add,
> remove, iteration, and in, with uniqueness what I care most about.
> 
> I know I could use bool[E] and set[element] = false, or I suppose
> container.rbtree. Would either of these--or something else built-in or
> in the std. lib.--be better?

bool[E] works just fine.

The bool does take up 1 byte, though, so if you're *really* want to
optimize that away, you could do this:

	alias Unit = void[0];
	enum unit = Unit.init;

	// Look, ma! A bona fide set!
	Unit[E] mySet;

	mySet[...] = unit;
	mySet.remove(...);
	... // etc.

Or you can wrap void[0][E] in a nice user-defined type that gives nice
set-like syntax.  But IMO, this is all overkill, and adds needless
complexity. Just use bool[E] or std.container.rbtree. :-D


T

-- 
If you look at a thing nine hundred and ninety-nine times, you are perfectly safe; if you look at it the thousandth time, you are in frightful danger of seeing it for the first time. -- G. K. Chesterton


More information about the Digitalmars-d-learn mailing list