[英]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>
實例后調用終止
我也試過使用子索引而不是迭代器,得到同樣的錯誤。
我確定我做錯了什么,我只是看不到它。
迭代映射時,迭代器指向一對鍵/值對節點,而不是單個節點。 例如:
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 循環的選項,如下所示:
for(const auto& characterType : node["characterType"]) {
std::string key = characterType.first.as<std::string>();
cTypeList.push_back(characterType.second.as<CharacterType>());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.