数据结构与yaml-cpp接口的设计技巧
Design tips for data structures to interface with yaml-cpp?
我开始使用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;
相关文章:
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 使用 yaml-cpp 更新 YAML 文档的节点和值
- 使用 yaml-cpp 解析 YAML 文件
- 使用 pybind11 包装 yaml-cpp 迭代器
- 编辑单个 YAML 值,而不更新 YAML (YAML CPP) 其余部分的格式
- 常量 yaml-cpp 节点在多次使用时会发生变化
- 为什么 const YAML::Node 对象的行为不像 yaml-cpp 中的类似值的对象?
- yaml-cpp到std::向量迭代的怪异行为
- 为 yaml-cpp 库查找正确的 cmake 配置
- YAML-CPP 编码/解码指针?
- yaml-cpp 比较的意外结果
- YAML-cpp 编译错误:"undefined reference to YAML::LoadFile"
- Yaml-cpp:在发射器中的每个新映射之前禁用自动开始文档 (---)
- 如何在yaml-cpp中写一个版本字符串作为文字(不是字符串)
- 使用YAML -CPP新API - 已修复的YAML文件解决
- 在yaml-cpp中,是否可以获取文档中的顶级键名
- YAML-CPP的顺序返回数据
- YAML-cpp 解析嵌套映射和序列错误
- 如何通过命令行在Visual Studio/cmake上构建yaml-cpp?
- 数据结构与yaml-cpp接口的设计技巧