Using sets in associative arrays

Olivier Pisano olivier.pisano at laposte.net
Tue Nov 12 06:42:19 UTC 2024


Hello,

In your case, the type "set of integers" would be written as 
`RedBlackTree!int` in D. Note that it starts with an uppercase R, 
and takes the type of values to contain as template argument (the 
int after the exclamation mark).

Btw, in the standard library, types always start with an 
uppercase character, it is a convention that will help you later.

I can then use this type to declare an associated array of sets 
of integers such as


     void main()
     {
         RedBlackTree!int[int] assoset;
         assoset[2] = redBlackTree(2, 3, 4, 5);
     }


In my example the first line declares an empty associative array 
that maps sets of integers to integers. I believe this is what 
you wanted.

The second line may look a bit confusing : `redBlackTree` starts 
with a lowercase character and does not contain template type 
argument. It is a function, not a type. This function takes 
variadic arguments and creates a `RedBlackTree` of the type of 
its arguments. Here, `2, 3, 4, 5` are ints, so it returns a 
`RedBlackTree!int`. You may think of it like a constructor or a 
factory function.

The standard library is full of these convenience functions, 
because function templates, contrary to struct/class templates, 
can deduce their template arguments, and avoid the need of 
precising every detail when it is obsvious.

I hope it helps.










More information about the Digitalmars-d-learn mailing list