数据结构的设计技巧是否与yaml-cpp接口?

时间:2012-02-09 14:46:28

标签: c++ yaml yaml-cpp

我开始使用YAML和yaml-cpp库来解释我的文件。我用我自己的项目中的一些信息扩展了“怪物”的例子。代码和yaml文件如下,但首先是我的问题:

是否有必要将我将从项目中获得的所有数据放入一个庞大的结构中?在怪物示例中,从文档doc [i]中读取值很容易,因为它是一个怪物列表。在我的例子中,我将有一些列表,但也有标量等。我发现这样做的唯一方法是制作一个技术上只有一个条目的列表(即,顶部有一个' - '的文件,一切都缩进一个块)。我认为答案是采取过载>>的'问题制定'版本的一些内容。运算符,但如果没有该函数内的内容,我无法正常工作。任何帮助或建议表示赞赏。

ea_test.cpp:

    #include "yaml-cpp/yaml.h"
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>

    struct Vec2{
  double x, y;
    };

    struct DecVar{
  std::string name;
  std::string tag;
      Vec2 range;
  std::string description;
    };

    struct ProblemFormulation{
  std::vector <DecVar> decvars;
  int numrealizations;
    };

    void operator >> (const YAML::Node& node, Vec2& v) {
  node[0] >> v.x;
  node[1] >> v.y;
    }

    void operator >> (const YAML::Node& node, DecVar& decvar){
  node["name"] >> decvar.name;
  node["tag"] >> decvar.tag;
      node["range"] >> decvar.range;
  node["description"] >> decvar.description;
    }

    void operator >> (const YAML::Node& node, ProblemFormulation& problemformulation){
      node["realizations"] >> problemformulation.numrealizations;
      std::cout << " read realizations!" << std::endl; 
      const YAML::Node& decvarNode = node["decisions"];
      for (unsigned int i = 0; i < decvarNode.size(); i++)
      {
    DecVar decvar;
    decvarNode[i] >> decvar;
        problemformulation.decvars.push_back(decvar);
      }
    }

    int main()
    {
        std::ifstream fin("./ea.yaml");
        YAML::Parser parser(fin);
        YAML::Node doc;
        parser.GetNextDocument(doc);
        std::cout << "entering loop" << std::endl;

        ProblemFormulation problemformulation;

        for (unsigned int i = 0; i < doc.size(); i++)
        {
              doc[i] >> problemformulation;
        }
        return 0;
    }

而且,ea.yaml:

    -
      realizations: 10
      decisions:
        - name: reservoir
          tag: res_tag
          range: [0, 1.0]
          description: >
            This is a description.
        - name: flow
          tag: flow_tag
          range: [0, 2.0]
          description: >
            This is how much flow is in the system.

提前感谢您的帮助和提示!

编辑:我可能只会运行一个yaml文档,并且只会创建一个problemformulation对象。我的代码会调整您为列表执行的操作,但只执行一次。我想知道正确的方法,“只做一次”,因为我认为这样会更清晰并且制作一个更好看的YAML文件(没有任何东西无缘无故地缩进一个块)。

1 个答案:

答案 0 :(得分:1)

写作时

for (unsigned int i = 0; i < doc.size(); i++)
{
    doc[i] >> problemformulation;
}

这将遍历[假定为序列]文档中的所有条目并读取每个条目。如果你的顶级节点不是一个序列节点,而是一个&#34;问题公式&#34;,那么就写一下

doc >> problemformulation;