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