如何确定在yaml-cpp中处理的节点类型
How do you determine what kind of node you are dealing with in yaml-cpp?
我在这里阅读教程代码:https://code.google.com/p/yaml-cpp/wiki/Tutorial
一个例子是这样的:
YAML::Node primes = YAML::Load("[2, 3, 5, 7, 11]");
for (YAML::const_iterator it=primes.begin();it!=primes.end();++it) {
std::cout << it->as<int>() << "n";
}
下一个是这样的:
YAML::Node lineup = YAML::Load("{1B: Prince Fielder, 2B: Rickie Weeks, LF: Ryan Braun}");
for(YAML::const_iterator it=lineup.begin();it!=lineup.end();++it) {
std::cout << "Playing at " << it->first.as<std::string>() << " is " << it->second.as<std::string>() << "n";
}
然而,如果您在这两种情况之间交换YAML文件,您将得到一个错误,因为您正在访问序列的映射迭代器,反之亦然:
terminate called after throwing an instance of 'YAML::InvalidNode'
what(): yaml-cpp: error at line 0, column 0: invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa
对于任意的YAML输入,我如何在不使用try/catch块的情况下确定我是在处理循环中的序列还是映射(即我是否应该首先使用->)?
我试着找文件,但找不到
更新:
这就是我要做的:
YAML::Node config = YAML::LoadFile(filename);
for (YAML::const_iterator it=config.begin();it!=config.end();++it) {
if (it->Type() == YAML::NodeType::Map) { // exception
std::cout << it->first.as<std::string>();
} else if (it->Type() == YAML::NodeType::Sequence) {
std::cout << it->as<std::string>();
}
}
但是当我运行代码时,我会得到如上所述的异常。它编译得很好。
我使用的是ubuntu 14.04(0.5.1)附带的yaml-cpp。
您可以选择
switch (node.Type()) {
case Null: // ...
case Scalar: // ...
case Sequence: // ...
case Map: // ...
case Undefined: // ...
}
或显式查询,例如:
if (node.IsSequence()) {
// ...
}
(我在教程中添加了这一点。)
编辑:在您的特定示例中,您应该在迭代之前检查config.Type()
,而不是在迭代期间检查任何节点的类型。
相关文章:
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 无法使用类型为"结构节点 *"的左值初始化类型为"结构节点 *"的参数
- C++错误(从不兼容的类型"void"分配给树节点*)
- 创建的节点类型不同
- 基于给定字符串数据类型的链表删除节点
- 媒体基础获取拓扑节点的 IMFMedia类型
- 如何使用指针连接两种不同的节点类型(结构)?
- 如何在没有动态调用的情况下确定子节点的类型
- 查找树(不属于任何特定类型的简单连接树)中两个节点之间的路径
- 当我返回节点*时,C++中出现未知类型错误
- 我不知道如何调用参数为节点类型的函数
- 联合而不是aligned_storage_t作为容器节点类型的一部分
- 如何将不同类型的节点存储在一个链接列表中
- 如何使用同一链接列表一次处理各种类型的节点
- 错误 - 列表节点未命名类型
- 如何为链接列表节点定义一个以指针为模板类型的模板类
- 使用公共类函数初始化节点类型<Type>指针C++
- 错误:请求"cur"中的成员"成员",该成员属于非类类型节点<int>* 二叉树
- 如何将列表'node_ptr'转换为我自己的节点类型
- 如何确定在yaml-cpp中处理的节点类型