gpt4 book ai didi

c++ - Yaml-cpp(新 API): Problems mixing maps and scalars in a sequence

转载 作者:太空狗 更新时间:2023-10-29 21:00:15 34 4
gpt4 key购买 nike

我在解析这种形式的 yaml 文件时遇到了一个非常简单的问题:

- Foo
- Bar:
b1: 5

我想将顶级键解析为字符串,即“Foo”和“Bar”。如您所见,序列中的第一个条目是标量,第二个条目是包含一个键/值对的映射。假设我已将此 YAML 文本加载到名为 config 的节点中。我以下列方式遍历配置:

YAML::Node::const_iterator n_it = config.begin();
for (; n_it != config.end(); n_it++) {
std::string name;
if (n_it->Type() == YAML::NodeType::Scalar)
name = n_it->as<std::string>();
else if (n_it->Type() == YAML::NodeType::Map) {
name = n_it->first.as<std::string>();
}
}

问题在于解析第二个“Bar”条目。我收到以下 yaml-cpp 异常,告诉我我正在尝试从序列迭代器 n_it 访问 key 。

YAML::InvalidNode: yaml-cpp: error at line 0, column 0: invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa

如果我更改对此的访问权限:

name = n_it->as<std::string>();

我得到一个不同的 yaml-cpp 异常,我猜这是因为我试图将整个 map 作为 std::string 访问

YAML::TypedBadConversion<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >: yaml-cpp: error at line 0, column 0: bad conversion

谁能给我解释一下这是怎么回事?

编辑:新问题我仍然对此 api 处理 map 与序列有问题。现在说我有以下结构:

foo_map["f1"] = "one";
foo_map["f2"] = "two";
bar_map["b1"] = "one";
bar_map["b2"] = "two";

我希望将其转换为以下 YAML 文件:

Node: 
- Foo:
f1 : one
f2 : two
- Bar:
b1 : one
b2 : two

我会这样做:

node.push_back("Foo");
node["Foo"]["b1"] = "one";
...
node.push_back("Bar");

但是在最后一行节点现在已经从一个序列转换为一个映射并且我得到一个异常。我能做到这一点的唯一方法是输出 map 的 map :

Node:
Foo:
f1 : one
f2 : two
Bar:
b1 : one
b2 : two

问题是如果我无法读回此类文件。如果我遍历 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
}
}

这应该很容易处理,但一直让我发疯!

最佳答案

在你的表达中

name = n_it->first.as<std::string>();

n_it 是一个序列迭代器(因为它是您的顶级节点的迭代器),您刚刚建立了指向 map 的点。也就是说,

YAML::Node n = *n_it;

是 map 节点。这个 map 节点(在你的例子中)看起来像:

Bar:
b1: 5

换句话说,它有一个键/值对,键是一个字符串,值是一个映射节点。听起来你想要字符串键。所以:

assert(n.size() == 1);  // Verify that there is, in fact, only one key/value pair
YAML::Node::const_iterator sub_it = n.begin(); // This iterator points to
// the single key/value pair
name = sub_it->first.as<std::string>();

关于c++ - Yaml-cpp(新 API): Problems mixing maps and scalars in a sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459551/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com