使用 yaml-cpp 读取地图矢量失败

Reading a vector of maps with yaml-cpp fails

我想读取以下yaml数据:

camera:
 response_values: [[0.0: 0.0, 1.0: 1.1, 245.0: 250.1], [0.0: 0.1, 1.0: 1.3, 200.0: 250], [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]]

我想把它读成vector < map <float, float> >。在这种情况下,向量将有 3 个映射,每 3 个映射。

我的尝试是这样的:

#include <yaml-cpp/yaml.h>
#include <fstream>
#include <map>

using namespace std;

int main()
{

  YAML::Node camerafile = YAML::LoadFile("/path/to/camera.yaml");

  YAML::Node camera = camerafile["camera"];

  auto response_values_yaml = camera["response_values"];
  for(YAML::const_iterator it=response_values_yaml.begin();it!=response_values_yaml.end();++it) {
    YAML::Node response_values_map = it->as<YAML::Node>(); // e.g. [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]
    string whole_map = YAML::Dump(response_values_map);

    for(YAML::const_iterator at=response_values_map.begin();at!=response_values_map.end();++at) {
      auto the_thing = at->as<YAML::Node>();
      string the_string = YAML::Dump(the_thing);
      float key = at->first.as<float>();
      float val = at->second.as<float>();
    }
  }
}

调试结果:
whole_map: "[{0.0: 0.0}, {1.0: 1.1}, {245.0: 250.1}]"
the_string: "{0.0: 0.0}"
the_thing->Node->Ref->Data有一个map项

但是,程序一达到 float key = at->first.as<float>();,就崩溃了。

terminate called after throwing an instance of 'YAML::InvalidNode'
  what():  invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa

GDB 跳转到 yaml-cpp/node/imlp.hthis 是一个空节点,m_isValidfalse

尝试 as<string> 会产生相同的行为。我想我有一张地图,但我不能将其解释为使用 .first.second 方法的地图,我认为这就是错误消息告诉我的内容。我错过了什么?

#include <assert.h>
#include <fstream>
#include <iostream>
#include <map>
#include <yaml-cpp/yaml.h>

using namespace std;

int main() {

  YAML::Node camerafile = YAML::LoadFile("./camera.yaml");

  YAML::Node camera = camerafile["camera"];

  auto response_values_yaml = camera["response_values"];
  // it is the sequence iterator
  for (YAML::const_iterator it = response_values_yaml.begin();
       it != response_values_yaml.end(); ++it) {
    YAML::Node response_values_map
        = it->as<YAML::Node>(); // e.g. [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]

    for (YAML::const_iterator at = response_values_map.begin();
         at != response_values_map.end(); ++at) {


      // `at` is a **map iterater** which has a single key/value pair.
      // so it will certainly coredump when you are calling `at->first.as<float>()`
      assert(at->size() == 1);
      // The iterator points to the single key/value pair.
      YAML::Node::const_iterator sub_it = at->begin(); // **The key point.**
      // Then access the key and value.
      float key = sub_it->first.as<float>();
      float value = sub_it->second.as<float>();
      std::cout << " key: " << key << ", val: " << value << '\n';


    }
  }
}

输出将如下所示:

 key: 0, val: 0
 key: 1, val: 1.1
 key: 245, val: 250.1
 key: 0, val: 0.1
 key: 1, val: 1.3
 key: 200, val: 250
 key: 0, val: 0
 key: 1, val: 1.1
 key: 245, val: 250.1