Am I getting this all right?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Thu Dec 14 16:04:00 PST 2006
"Jason House" <jhouse at mitre.org> wrote in message
news:elsctg$5ca$1 at digitaldaemon.com...
> An earlier post showed stack with push and pop for an array. How does one
> do a
> queue? a set?
You could also use an associative array to model a set.
bool[int] set;
set[4] = true;
set[6] = true;
set[10] = true;
if(4 in set)
writefln("4 is in the set");
foreach(v, nothing; set)
writefln(v);
set.remove(6);
The "nothing" in the foreach loop is because the values in the associative
array are useless -- they're just there because they have to be.
In fact, why don't I just make a little set class to make it a little
prettier.
class Set(T)
{
protected bool[T] mData;
public this()
{
}
public void add(T value)
{
mData[value] = true;
}
public bool opIn_r(T value)
{
return ((value in mData) !is null);
}
public int opApply(int delegate(inout T value) dg)
{
int result = 0;
foreach(value, n; mData)
{
result = dg(value);
if(result)
break;
}
return result;
}
public void remove(T value)
{
mData.remove(value);
}
}
void main()
{
auto scope set = new Set!(int);
set.add(4);
set.add(6);
set.add(10);
if(4 in set)
writefln("4 is in the set");
foreach(v; set)
writefln(v);
set.remove(6);
}
More information about the Digitalmars-d-learn
mailing list