我想在不知道键的情况下获取 map 中的每个节点。
我的 YAML 如下所示:
characterType :
type1 :
attribute1 : something
attribute2 : something
type2 :
attribute1 : something
attribute2 : something
我不知道要声明多少个“类型”,也不知道这些键的名称是什么。这就是我尝试遍历 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>());
}
之前的代码在编译时没有任何问题,但是在执行时我得到了这个错误:
在抛出 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
}
(即使您的节点是 map 节点,您的代码编译的原因是 YAML::Node
是有效的动态类型,因此它的迭代器必须(静态地)充当序列迭代器和映射迭代器。)
关于c++ - yaml-cpp 遍历未定义值的 map 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12374691/