我对这个api处理地图与序列的处理有很基本的问题.说我有以下结构:
foo_map["f1"] = "one";
foo_map["f2"] = "two";
bar_map["b1"] = "one";
bar_map["b2"] = "two";
Run Code Online (Sandbox Code Playgroud)
我希望将其转换为以下YAML文件:
Node:
- Foo:
f1 : one
f2 : two
- Bar:
b1 : one
b2 : two
Run Code Online (Sandbox Code Playgroud)
我会这样做:
node.push_back("Foo");
node["Foo"]["b1"] = "one";
...
node.push_back("Bar");
Run Code Online (Sandbox Code Playgroud)
但是在最后一行节点现在已经从一个序列转换为一个映射,我得到了一个例外.我能做到这一点的唯一方法是输出地图地图:
Node:
Foo:
f1 : one
f2 : two
Bar:
b1 : one
b2 : two
Run Code Online (Sandbox Code Playgroud)
这个问题是我无法读回这些文件.如果我迭代Node,我甚至无法获得节点迭代器的类型而不会出现异常.
YAML::Node::const_iterator n_it = node.begin();
for (; n_it != config.end(); n_it++) {
if (n_it->Type() == YAML::NodeType::Scalar) {
// throws exception
}
}
Run Code Online (Sandbox Code Playgroud)
这应该很容易处理,但一直让我发疯!
The YAML file
Node:
- Foo:
f1 : one
f2 : two
- Bar:
b1 : one
b2 : two
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
}
}
Run Code Online (Sandbox Code Playgroud)