[英]yaml-cpp Easiest way to iterate through a map with undefined values
I'd like to obtain every node in a map without knowing the keys.我想在不知道键的情况下获取地图中的每个节点。
My YAML looks like this:我的 YAML 看起来像这样:
characterType :
type1 :
attribute1 : something
attribute2 : something
type2 :
attribute1 : something
attribute2 : something
I don't know how many "type"s will be declared or what the name of those keys will be.我不知道将声明多少“类型”或这些键的名称是什么。 That's why I'm trying to iterate through the map.
这就是为什么我试图遍历地图。
struct CharacterType{
std::string attribute1;
std::string attribute2;
};
namespace YAML{
template<>
struct convert<CharacterType>{
static bool decode(const Node& node, CharacterType& cType){
cType.attribute1 = node["attribute1"].as<std::string>();
cType.attribute2 = node["attribute2"].as<std::string>();
return true;
}
};
}
---------------------
std::vector<CharacterType> cTypeList;
for(YAML::const_iterator it=node["characterType"].begin(); it != node["characterType"].end(); ++it){
cTypeList.push_back(it->as<CharacterType>());
}
The previous code doesn't give any trouble when compiling but then at execution time I get this error: terminate called after throwing an instance of YAML::TypedBadConversion<CharacterType>
前面的代码在编译时没有出现任何问题,但在执行时我收到此错误:在抛出
YAML::TypedBadConversion<CharacterType>
实例后调用终止
I've also tried using a subindex instead of the iterator, getting the same error.我也试过使用子索引而不是迭代器,得到同样的错误。
I'm sure I'm doing something wrong, I just can't see it.我确定我做错了什么,我只是看不到它。
When you iterate through a map, the iterator points to a key/value pair of nodes, not a single node. 迭代映射时,迭代器指向一对键/值对节点,而不是单个节点。 For example:
例如:
YAML::Node characterType = node["characterType"];
for(YAML::const_iterator it=characterType.begin();it != characterType.end();++it) {
std::string key = it->first.as<std::string>(); // <- key
cTypeList.push_back(it->second.as<CharacterType>()); // <- value
}
(The reason that your code compiled, even though your node is a map node, is that YAML::Node
is effectively dynamically typed, so its iterator has to act (statically) as both a sequence iterator and a map iterator.) (即使您的节点是一个映射节点,您的代码编译的原因是
YAML::Node
实际上是动态类型的,因此它的迭代器必须(静态地)作为序列迭代器和映射迭代器。)
The answer from @jesse-beder is right, I give just another option with using range-based for loop like below: @jesse-beder 的答案是正确的,我给出了另一个使用基于范围的 for 循环的选项,如下所示:
for(const auto& characterType : node["characterType"]) {
std::string key = characterType.first.as<std::string>();
cTypeList.push_back(characterType.second.as<CharacterType>());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.