问题描述
我正在尝试使用 yaml-cpp
为我的应用程序创建配置文件,我可以通过
map
YAML::Emitter emitter;
emitter << YAML::BeginMap;
emitter << YAML::Key << "Autoplay" << YAML::Value << "false";
emitter << YAML::EndMap;
std::ofstream ofout(file);
ofout << emitter.c_str();
输出类似,
var1: value1
var2: value2
但是我将如何制作顶部对象,
Foo:
var1: value1
var2: value2
Bar:
var3: value3
var4: value4
等等.. 我如何获得上面代码中的 Foo
和 Bar
。
解决方法
您想要实现的是一个包含两个键 Foo 和 Bar 的映射。每个都包含一个地图作为值。下面的代码向您展示了如何实现这一目标:
// gcc -o example example.cpp -lyaml-cpp
#include <yaml-cpp/yaml.h>
#include <fstream>
int main() {
std::string file{"example.yaml"};
YAML::Emitter emitter;
emitter << YAML::BeginMap;
emitter << YAML::Key << "Foo" << YAML::Value;
emitter << YAML::BeginMap; // this map is the value associated with the key "Foo"
emitter << YAML::Key << "var1" << YAML::Value << "value1";
emitter << YAML::Key << "var2" << YAML::Value << "value2";
emitter << YAML::EndMap;
emitter << YAML::Key << "Bar" << YAML::Value;
emitter << YAML::BeginMap; // This map is the value associated with the key "Bar"
emitter << YAML::Key << "var3" << YAML::Value << "value3";
emitter << YAML::Key << "var4" << YAML::Value << "value4";
emitter << YAML::EndMap;
emitter << YAML::EndMap; // This ends the map containing the keys "Foo" and "Bar"
std::ofstream ofout(file);
ofout << emitter.c_str();
return 0;
}
您必须以递归的心态看待这些类型的结构。此代码将创建您提供的示例。