Yaml-cpp (new API) - nested map / sequence combinations and iteration

前端 未结 1 1540
猫巷女王i
猫巷女王i 2021-01-14 21:49

I\'m having quite fundamental problems with this api\'s handling of maps vs sequences. Say I have the following structure:

foo_map[\"f1\"] = \"one\";
foo_ma         


        
1条回答
  •  被撕碎了的回忆
    2021-01-14 22:18

    The YAML file

    Node: 
        - Foo:
          f1 : one
          f2 : two
        - Bar:
          b1 : one
          b2 : two
    

    is probably not what you expect. It is a map, with a single key/value pair; the key is Node and the value is a sequence; and each entry of that sequence is a map with three key/value pairs, and the value associated with, e.g., the Foo, is null. This last part is probably not what you expected. I'm guessing you wanted something more like what you actually got, i.e.:

    Node:
        Foo:
          f1 : one
          f2 : two
        Bar:
          b1 : one
          b2 : two
    

    The question now is how to parse this structure.

    YAML::Node root = /* ... */;
    YAML::Node node = root["Node"];
    
    // We now have a map node, so let's iterate through:
    for (auto it = node.begin(); it != node.end(); ++it) {
      YAML::Node key = it->first;
      YAML::Node value = it->second;
      if (key.Type() == YAML::NodeType::Scalar) {
        // This should be true; do something here with the scalar key.
      }
      if (value.Type() == YAML::NodeType::Map) {
        // This should be true; do something here with the map.
      }
    }
    

    0 讨论(0)
提交回复
热议问题