使用std::initializer_list创建树
Using std::initializer_list to create a tree?
我所拥有的是:
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 } } } };
(在实践中,您可能希望将i
和c
组合)
下面是一个实例。
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 << ")";
}
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 使用std::list创建循环链表
- 返回在函数中创建的 std::list 的第一个节点
- 在std::list中就地创建自定义类型对象
- 您将如何为 std::list<std::string> 创建一个类型映射,以在<String> List in C++ 中为 Java 在 SWIG 中创建?
- 在递归函数中创建 std::list of value 而不是 std::list of 指针
- C++在函数中创建std::list并通过参数返回
- 无法在 qml 中创建C++类对象"Cannot assign object to list property "数据" "
- 如何在c++中使用std::list迭代器存储在std vector中,创建复制安全容器
- 使用标准模板库list或vector和multimap创建电话号码簿