【问题标题】:How do you determine what kind of node you are dealing with in yaml-cpp?你如何确定你在 yaml-cpp 中处理什么样的节点?
【发布时间】:2014-10-03 13:19:12
【问题描述】:

我正在这里阅读教程代码: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 块的情况下,如何确定我是在处理循环中的序列还是映射(即是否应该使用 ->first 或不使用)?

我尝试查找文档,但找不到。

更新

这就是我想要做的:

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。

【问题讨论】:

    标签: c++ yaml-cpp


    【解决方案1】:

    你可以

    switch (node.Type()) {
      case Null: // ...
      case Scalar: // ...
      case Sequence: // ...
      case Map: // ...
      case Undefined: // ...
    }
    

    或显式查询,例如:

    if (node.IsSequence()) {
      // ...
    }
    

    (我在教程中添加了这一点。)

    编辑:在您的具体示例中,您应该在迭代之前检查config.Type(),而不是在迭代期间检查任何节点的类型。

    【讨论】:

    • 感谢您的回答 Jesse,但我不太确定这如何解决我遇到的问题。我的问题是我不知道如何获取可以调用这些函数的节点对象。我已将我要编写的代码添加到我的问题中。
    • @jeremy,我为您的具体示例更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多