yaml-cpp迭代具有未定义值的映射的最简单方法

yaml-cpp Easiest way to iterate through a map with undefined values

本文关键字:映射 最简单 方法 未定义 迭代 yaml-cpp      更新时间:2023-10-16

我想在不知道键的情况下获得映射中的每个节点。

我的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> 实例后调用的terminate

我还尝试使用子索引而不是迭代器,得到了同样的错误。

我确信我做错了什么,我就是看不见。

在映射中迭代时,迭代器指向一对键/值节点,而不是单个节点。例如:

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(const auto& characterType : node["characterType"]) {
   std::string key = characterType.first.as<std::string>();
   cTypeList.push_back(characterType.second.as<CharacterType>());
}