c++ - yaml-cpp 遍历未定义值的 map 的最简单方法

标签 c++ yaml-cpp

我想在不知道键的情况下获取 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/

相关文章:

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

子类中的 C++ 收紧函数参数类型

c++ - 默认情况下,pragma 一次应该位于每个标题的顶部

c++ - 如何在C/C++中创建一个新进程并在WinXp中获取这个新进程句柄?

c++ - yaml-cpp 0.5.1 的可选 key

c++ - 构建一个 C++ Linux 程序。何时拆分单独的文件与单独的程序

c++ - 带有空格的 yaml-cpp 格式映射

c++ - 使用 yaml cpp 解析 yaml

c++ - 如何在 YAML 中发出以逗号分隔的列表

c++ - 如何在我的 CMakelists.txt 中链接 yaml-cpp?