How do I declare an array of red black trees?

Viewed 87

When I want to initialize a red black tree I do as in the documentation.

auto rbt = redBlackTree(1,2,3,4)

but if I want to declare it globally or make an array of red black trees I don't know how to do it and the documentation is not helping. I've tried various things and I frequently get errors similar to: redBlackTree!int is used as a type Can you help me? I could do it if I knew what to put instead of auto, ie, if I knew the type of redBlackTree.

I want to declare a red black tree in global scope or declare an array for which I need to declare the type, I want to do something like this:

type rbt;
void main() {
    rbt.insert(3);
}

or this:

void main{
    type[2] rbt;
    rbt[0].insert(1);
}
2 Answers

You don't need to know the type of redBlackTree. You can query for at compile-time with typeof:

alias RBTree = typeof(redBlackTree(1));
RBTree rbt = redBlackTree(1, 2, 3);

This is a common and an encouraged pattern as many functions in D return Voldemort types (types that cannot be named).

In your example the type is RedBlackTree!int. If you don't use an IDE, an easy way to discover the type is pragma(msg, typeof(<functionCall>(<args>)));. Furthermore, I should note that declaring an array of RedBlackTree works with auto:

auto arr = [redBlackTree(1, 2), redBlackTree(3, 4)];

For more help, please feel free to post the exact code that failed.

The type (using long instead of int) is RedBlackTree!long, here are some examples. Remember you have to use new to initialize the class.

import std.stdio;
import std.container;

RedBlackTree!long rbtree;
RedBlackTree!long[2] rbarray;
RedBlackTree!long[] rbdynamicarr;
RedBlackTree!long[][] rbmat;

void main() {
    rbtree.writeln;
    rbtree = new RedBlackTree!long;
    rbtree.insert(3);
    rbtree.writeln;

    rbarray.writeln;
    rbarray = new RedBlackTree!long[2];
    rbarray.writeln;

    rbdynamicarr.writeln;
    int n = 3;
    rbdynamicarr = new RedBlackTree!long[n];
    rbdynamicarr.writeln;

    rbmat.writeln;
    int m = 2;
    rbmat = new RedBlackTree!long[][](n,m);
    rbmat.writeln;

    alias RBTree = typeof(redBlackTree!long(1L));
    RBTree rbalias;
    rbalias = new RBTree;
    rbalias.writeln;

    RBTree[3] crayola;
    crayola.writeln;

    typeid(redBlackTree(1)).writeln;
    RedBlackTree!(long, "a < b", false) hola;
    hola = new RedBlackTree!(long, "a < b", false);
    hola.writeln;
}
Related