使用std::initializer_list创建树

Using std::initializer_list to create a tree?

本文关键字:创建 list initializer std 使用      更新时间:2023-10-16

我所拥有的是:

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

我想写的是这样的:

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

我可以自由地定义MyTree类(以及可能的helper类)-但它应该是类似于树的操作符,作为TreeNode内容和容器(例如std::vector)保存子节点。

在c++中,是否可以使用这样的initializer_list来初始化树状结构?(如果可能的话,一个提示如何做到这一点将是很好的。)

下面可能对你有用:

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 } } } };

(在实践中,您可能希望将ic组合)

下面是一个实例。


Update:正如在我使用类似技术的另一个Q/A中指出的那样,上面是未定义的行为,因为我使用std::vector<ExprTreeNode>作为成员,在那一点上,ExprTreeNode不是一个完整的类型。下面的代码可以修复它:

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))
{}

这也使用shared_ptr作为叶子/非叶子的标志,如果你想使用它,你需要先转换它:

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 << ")";
   }
}