如何确定在yaml-cpp中处理的节点类型

How do you determine what kind of node you are dealing with in yaml-cpp?

本文关键字:节点 类型 处理 何确定 yaml-cpp      更新时间:2023-10-16

我在这里阅读教程代码: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(),而不是在迭代期间检查任何节点的类型。