c++yaml-cpp

Seemingly unnecessary indexing when traversing yaml-cp nodes


I'm trying to use the following C++ program

#include <iostream>
#include <yaml-cpp/yaml.h>

int main() {
    YAML::Node config = YAML::LoadFile("test.yaml");
    YAML::Node machine = config["cluster"][0];

    std::cout << machine << std::endl;
    std::cout << "-----" << std::endl;
    std::cout << machine["num_cores"] << std::endl;
    std::cout << "-----" << std::endl;
    std::cout << machine[1] << std::endl;   // Why is index-1 required??
    std::cout << "-----" << std::endl;
    std::cout << machine[1]["num_cores"] << std::endl;

    return 0;
}

to parse the YAML file

cluster:
  - 1:
      num_cores: 4
      memory_in_gb: 64
  - 2:
      num_cores: 2
      memory_in_gb: 32

Program output:

1:
  num_cores: 4
  memory_in_gb: 64
-----

-----
num_cores: 4
memory_in_gb: 64
-----
4

Everything seems great apart from the fact that machine["num_cores"] returns nothing. And I seem to require an unnecessary indexing machine[1]["num_cores"] in order to get at the num_cores of a node in the cluster.

What's going on here? Am I doing something wrong?


Solution

  • cluster[0] is a map, with a single key “1”, whose value is a map. Hence the extra index (into the map of one key/value pair).