18

キーを知らなくても、マップ内のすべてのノードを取得したいのですが。

私の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>

イテレータの代わりにサブインデックスを使用しようとしましたが、同じエラーが発生しました。

私は何か間違ったことをしていると確信しています、私はそれを見ることができません。

4

2 に答える 2

27

マップを反復処理する場合、反復子は単一のノードではなく、ノードのキーと値のペアを指します。例えば:

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は、事実上動的に型付けされるため、そのイテレータはシーケンス イテレータとマップ イテレータの両方として (静的に) 動作する必要があります。)

于 2012-09-11T17:43:43.000 に答える