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

Design tips for data structures to interface with yaml-cpp?

本文关键字:yaml-cpp 接口 数据结构      更新时间:2023-10-16

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

有必要把我从项目中得到的所有数据都放在一个巨大的结构中吗?在怪物的例子中,从文档doc[i]中读取值很容易,因为它是一个怪物列表。在我的例子中,我会有一些列表,但也有标量等。我找到的唯一方法是制作一个从技术上讲只有一个条目的列表(即,在文件顶部有一个"-",所有内容都缩进到一个块中)。我认为答案是接受重载>>运算符的"problemformation"版本的一些内容,但如果没有该函数中的内容,我就无法使其正常工作。如有任何帮助或建议,我们将不胜感激。

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;
    }

而且,是的

    -
      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文档,并且只会创建一个problemformation对象。我的代码会调整您对列表所做的操作,但只做一次。我想知道"只做一次"的正确方法,因为我认为这会更干净,并制作出一个外观更好的YAML文件(没有所有东西无缘无故地缩进一个块)。

当您编写时

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

这将遍历[假定为序列]文档中的所有条目,并读取每个条目。如果您的顶级节点不是序列节点,而是"问题公式",那么只需编写

doc >> problemformulation;