c++ - Using std::initializer_list to create a tree? -


what have like:

struct exprtreenode {    char c;    std::vector< int > i; };  exprtreenode tn { '+', { 1, 2, 3, 4 } }; 

what want write like:

mytree t1 { '+', { 1, 2, { '*', { 3, 4, 5 } } } }; mytree t2 { '*', { { '+', { 77, 88, 99, 111 } }, { '-', { 44, 33 } } } }; 

i'm free define mytree class (and possible helper classes) - should tree-ish - operator treenode content , container (e.g. std::vector) holding subnodes.

in c++ possible use such initializer_list initialize tree-like structure? (if possible, hint how nice.)

the following might work you:

struct exprtreenode {     bool is_value;     int i;     char c;     std::vector< exprtreenode > v;      exprtreenode( int i_ ) : is_value( true ), i( i_ ) {}     exprtreenode( char c_, std::initializer_list< exprtreenode > v_ )       : is_value( false ), c( c_ ), v( v_ ) {} };  exprtreenode tn { '+', { 1, 2, { '*', { 3, 4 } } } }; 

(in practice might want combine i , c)

here's live example.


update: pointed out in q/a used similar technique, above undefined behaviour using std::vector<exprtreenode> member , @ point, exprtreenode not complete type. following should fix it:

struct exprtreenode {     int value_;     char op_;     std::shared_ptr< void > subnodes_;      exprtreenode( int v ) : value_( v ) {}     exprtreenode( char op, std::initializer_list< exprtreenode > subnodes );      void print() const; };  typedef std::vector< exprtreenode > nodes;  exprtreenode::exprtreenode( char op, std::initializer_list< exprtreenode > l )   : op_(op), subnodes_(std::make_shared<nodes>(l)) {} 

this uses shared_ptr flag leaf/non-leaf , if want use it, need cast first:

void exprtreenode::print() const {    if( !subnodes_ ) {       std::cout << value_;    }    else {       std::cout << op_ << " ( ";       for( const auto& e : *std::static_pointer_cast<nodes>(subnodes_) ) {          e.print(); std::cout << " ";       }       std::cout << ")";    } } 

here's updated live example.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -