如何用yaml-cpp创建top对象?

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

但是我怎样才能使顶部对象像,

Foo:
  var1: value1
  var2: value2

Bar:
  var3: value3
  var4: value4

等等..如何获得上面代码中的FooBar

你想要实现的是一个包含两个键 FooBar 的映射。其中每一个都包含一个地图作为值。下面的代码向您展示了如何实现这一点:

// 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;
}

你必须以递归的心态来看待这些结构。此代码将创建您提供的示例。