我想阅读以下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有一个映射项
然而,一旦程序到达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.h
。this
是一个空节点,m_isValid
是false
。
尝试as<string>
会产生同样的行为。我认为我有一个映射,但我不能用.first
和.second
方法将它解释为一个映射,我认为这就是错误消息告诉我的。我遗漏了什么?
发布于 2022-04-23 13:51:21
#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
https://stackoverflow.com/questions/71640946
复制相似问题