我想在不知道密钥的情况下获取地图中的每个节点.
我的YAML看起来像这样:
characterType :
type1 :
attribute1 : something
attribute2 : something
type2 :
attribute1 : something
attribute2 : something
Run Code Online (Sandbox Code Playgroud)
我不知道将声明多少"类型"或这些键的名称是什么.这就是我试图遍历地图的原因.
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>());
}
Run Code Online (Sandbox Code Playgroud)
以前的代码在编译时没有给出任何麻烦,但是在执行时我得到了这个错误:在抛出一个实例后调用terminate YAML::TypedBadConversion<CharacterType>
我也尝试使用子索引而不是迭代器,得到相同的错误.
我确定我做错了什么,我只是看不到它.
Jes*_*der 19
迭代映射时,迭代器指向一对键/值对节点,而不是单个节点.例如:
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
}
Run Code Online (Sandbox Code Playgroud)
(即使您的节点是一个映射节点,您的代码编译的原因是它YAML::Node是有效动态类型的,因此它的迭代器必须(静态地)作为序列迭代器和映射迭代器.)