问题描述
此api对地图和序列的处理存在一些非常基本的问题.说我有以下结构:
I'm having quite fundamental problems with this api's handling of maps vs sequences. Say I have the following structure:
foo_map["f1"] = "one";
foo_map["f2"] = "two";
bar_map["b1"] = "one";
bar_map["b2"] = "two";
我希望将其转换为以下YAML文件:
I want this to be converted to the following YAML file:
Node:
- Foo:
f1 : one
f2 : two
- Bar:
b1 : one
b2 : two
我可以这样做:
node.push_back("Foo");
node["Foo"]["b1"] = "one";
...
node.push_back("Bar");
但是,最后一行的节点现在已从序列转换为映射,但出现异常.我唯一的方法是输出地图:
However at the last line node has now been converted from a sequence to a map and I get an exception. The only way I can do this is by outputting a map of maps:
Node:
Foo:
f1 : one
f2 : two
Bar:
b1 : one
b2 : two
这是我无法读回此类文件的问题.如果我遍历Node,那么即使没有异常,我也无法获得节点迭代器的类型.
The problem with this is if I cannot read back such files. If I iterate over Node, I'm unable to even get the type of the node iterator without getting an exception.
YAML::Node::const_iterator n_it = node.begin();
for (; n_it != config.end(); n_it++) {
if (n_it->Type() == YAML::NodeType::Scalar) {
// throws exception
}
}
这应该很简单,但是一直让我发疯!
This should be very simple to handle but has been driving me crazy!
推荐答案
YAML文件
Node:
- Foo:
f1 : one
f2 : two
- Bar:
b1 : one
b2 : two
可能不是您所期望的.它是一个映射,具有单个键/值对;键是Node
,值是一个序列;并且该序列的每个条目都是具有三个键/值对的映射,并且与Foo
相关的值为null.最后一部分可能不是您期望的.我猜您想要的更像是您实际得到的东西,即:
is probably not what you expect. It is a map, with a single key/value pair; the key is Node
and the value is a sequence; and each entry of that sequence is a map with three key/value pairs, and the value associated with, e.g., the Foo
, is null. This last part is probably not what you expected. I'm guessing you wanted something more like what you actually got, i.e.:
Node:
Foo:
f1 : one
f2 : two
Bar:
b1 : one
b2 : two
现在的问题是如何解析此结构.
The question now is how to parse this structure.
YAML::Node root = /* ... */;
YAML::Node node = root["Node"];
// We now have a map node, so let's iterate through:
for (auto it = node.begin(); it != node.end(); ++it) {
YAML::Node key = it->first;
YAML::Node value = it->second;
if (key.Type() == YAML::NodeType::Scalar) {
// This should be true; do something here with the scalar key.
}
if (value.Type() == YAML::NodeType::Map) {
// This should be true; do something here with the map.
}
}
这篇关于Yaml-cpp(新API)-嵌套图/序列组合和迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!