Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用std::initializer\u list创建树?_C++_C++11_Initializer List - Fatal编程技术网

C++ 使用std::initializer\u list创建树?

C++ 使用std::initializer\u list创建树?,c++,c++11,initializer-list,C++,C++11,Initializer List,我所拥有的是: 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 } } } }; 我可以自由定

我所拥有的是:

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类(以及可能的助手类),但它应该是类似于树的操作符,作为树节点内容和包含子节点的容器(例如std::vector)


C++中有可能使用这样的初始化列表来初始化树型结构吗?(如果可能的话,给你一个提示就好了。)

以下内容可能适合你:

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 } } } };
这将
共享\u 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 << ")";
   }
}
void ExprTreeNode::print()常量
{
if(!子节点u2;){

谢谢你的回答。这很有帮助。
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 << ")";
   }
}