c – yaml-cpp以最简单的方式遍历具有未定义值的地图

我想获取地图中的每个节点,而不知道密钥.

我的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是有效的动态类型,因此它的迭代器必须作为序列迭代器和地图迭代器来动作(静态)).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...