[英]How to create the top object with yaml-cpp?
我正在嘗試使用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
但是我如何制作頂級 object 之類的,
Foo:
var1: value1
var2: value2
Bar:
var3: value3
var4: value4
等等..我如何獲得上面代碼中的Foo
和Bar
。
您想要實現的是包含兩個鍵Foo和Bar的 map 。 其中每一個都包含一個 map 作為值。 下面的代碼向您展示了如何實現這一目標:
// 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;
}
您必須以遞歸的心態看待這些結構。 此代碼將創建您提供的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.