[英]yaml-cpp Easiest way to iterate through a map with undefined values
我想在不知道键的情况下获取地图中的每个节点。
我的 YAML 看起来像这样:
characterType :
type1 :
attribute1 : something
attribute2 : something
type2 :
attribute1 : something
attribute2 : something
我不知道将声明多少“类型”或这些键的名称是什么。 这就是为什么我试图遍历地图。
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>());
}
前面的代码在编译时没有出现任何问题,但在执行时我收到此错误:在抛出YAML::TypedBadConversion<CharacterType>
实例后调用终止
我也试过使用子索引而不是迭代器,得到同样的错误。
我确定我做错了什么,我只是看不到它。
迭代映射时,迭代器指向一对键/值对节点,而不是单个节点。 例如:
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
}
(即使您的节点是一个映射节点,您的代码编译的原因是YAML::Node
实际上是动态类型的,因此它的迭代器必须(静态地)作为序列迭代器和映射迭代器。)
@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.