YAML-cpp 解析嵌套映射和序列错误

yaml-cpp parsing nested maps and sequences error

本文关键字:错误 映射 嵌套 YAML-cpp      更新时间:2023-10-16

我正在尝试解析一个带有嵌套映射和序列的文件,它有点像这样

annotations:
 - dodge:
   type: range based
   attributes:
    start_frame:
     frame_number: 25
     time_stamp: 2017-10-14 21:59:43
    endframe:
     frame_number: 39     
     time_stamp: 2017-10-14 21:59:45
    distances:
     - 2
     - 5
     - 6

我收到一条错误消息,指出确保节点存在。下面是我的示例代码。

YAML::Node basenode = YAML::LoadFile(filePath);
const YAML::Node& annotations = basenode["annotations"];
RangeBasedType rm;
for (YAML::const_iterator it = annotations.begin(); it != annotations.end(); ++it)
{
    const YAML::Node& gestures = *it;
    std::string type = gestures["type"].as<std::string>(); // this works
    rm.setGestureName(type);
    if (type == "range based")
    {
        const YAML::Node& attributes = gestures["attributes"];
        for (YAML::const_iterator ti = attributes.begin(); ti != attributes.end(); ++ti)
        {
            const YAML::Node& frame = *ti; 
            if (frame["start_frame"]) // this fails saying it is not a valid node
            {
                std::cout << frame["frame_number"].as<int>();
                rm.setStartFrame(frame["frame_number"].as<int>());
            }
        }
    }
}

我希望从节点start_frame和end_frame获取frame_number。我已经检查了 YAML 格式的有效性。为什么这不起作用的任何原因?

这个循环:

for (YAML::const_iterator ti = attributes.begin(); ti != attributes.end(); ++ti)

正在迭代映射节点。因此,迭代器指向键/值对。您的下一行:

const YAML::Node& frame = *ti;

取消将其作为节点引用。相反,您需要查看其键/值节点:

const YAML::Node& key = ti->first;
const YAML::Node& value = ti->second;

yaml-cpp允许迭代器指向节点和键/值对,因为它可以是映射或序列(或标量(,并且它是作为单个C++类型实现的。