我开始使用 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.
提前感谢您的帮助和提示!
Edit: I will probably only be running one yaml document, and there's only one problemformulation object that will ever be created. My code adapts what you'd do for a list, but only does it once. I would like to know the proper way to, "just do it once", since I think that would be cleaner and make a better looking YAML file (without all the things indented one block for no reason).