我正在尝试使用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的映射酒吧和。每一个都包含一个映射作为值。下面的代码向您展示了如何实现这一点:
// 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;
}
你必须用递归的心态来看待这些结构。这段代码将创建您给出的示例。