How to Populate a 'Tree' structure 'Declaratively'

Posted by mackenir on Stack Overflow See other posts from Stack Overflow or by mackenir
Published on 2012-11-23T15:16:35Z Indexed on 2012/11/24 17:04 UTC
Read the original article Hit count: 189

I want to define a 'node' class/struct and then declare a tree of these nodes in code in such a way that the way the code is formatted reflects the tree structure, and there's not 'too much' boiler plate in the way.

Note that this isn't a question about data structures, but rather about what features of C++ I could use to arrive at a similar style of declarative code to the example below.

Possibly with C++0X this would be easier as it has more capabilities in the area of constructing objects and collections, but I'm using Visual Studio 2008.

Example tree node type:

struct node
{ 
  string name;
  node* children;

  node(const char* name, node* children);
  node(const char* name);
};

What I want to do:

Declare a tree so its structure is reflected in the source code

node root =
  node("foo",
  [
    node("child1"),
    node("child2", 
    [
      node("grand_child1"),
      node("grand_child2"),
      node("grand_child3"
    ]),
    node("child3")
  ]);

NB: what I don't want to do:

Declare a whole bunch of temporary objects/colls and construct the tree 'backwards'

node grandkids[] = node[3] 
{
  node("grand_child1"),
  node("grand_child2"),
  node("grand_child3"
};

node kids[] = node[3]
{
  node("child1"),
  node("child2", grandkids) 
  node("child3")
};

node root = node("foo", kids);

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-studio-2008