yaml-cpp迭代具有未定义值的映射的最简单方法
yaml-cpp Easiest way to iterate through a map with undefined values
我想在不知道键的情况下获得映射中的每个节点。
我的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>());
}
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 请求最简单的 OpenMP 目标 GPU 示例
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- 对多个(可能)重叠范围进行分区的最简单算法
- 在 cpp 中最简单的图形实现
- boost::variant - 对变体应用算术的最简单方法
- 多线程 gtkmm 应用程序最简单的示例
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- 标准库容器最简单、性能差的哈希类是什么?
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 无法获得最简单的JNI足以在Windows 10上运行
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- yaml-cpp迭代具有未定义值的映射的最简单方法
- 读取映射到内存的CSV文件的最简单方法