1

怪物.yaml

- name: Ogre
      position: [0, 5, 0]
      powers:
        - name: Club
          damage: 10
        - name: Fist
          damage: 8
    - name: Dragon
      position: [1, 0, 10]
      powers:
        - name: Fire Breath
          damage: 25
        - name: Claws
          damage: 15
    - name: Wizard
      position: [5, -3, 0]
      powers:
        - name: Acid Rain
          damage: 50
        - name: Staff
          damage: 3

主文件

#include "yaml-cpp/yaml.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

// our data types
struct Vec3 {
   float x, y, z;
};

struct Power {
   std::string name;
   int damage;
};

struct Monster {
   std::string name;
   Vec3 position;
   std::vector <Power> powers;
};

// now the extraction operators for these types
void operator >> (const YAML::Node& node, Vec3& v) {
   node[0] >> v.x;
   node[1] >> v.y;
   node[2] >> v.z;
}

void operator >> (const YAML::Node& node, Power& power) {
   node["name"] >> power.name;
   node["damage"] >> power.damage;
}

void operator >> (const YAML::Node& node, Monster& monster) {
   node["name"] >> monster.name;
   node["position"] >> monster.position;
   const YAML::Node& powers = node["powers"];
   for(unsigned i=0;i<powers.size();i++) {
      Power power;
      powers[i] >> power;
      monster.powers.push_back(power);
   }
}

int main()
{
   std::ifstream fin("monsters.yaml");
   YAML::Parser parser(fin);
   YAML::Node doc;
   parser.GetNextDocument(doc);
   for(unsigned i=0;i<doc.size();i++) {
      Vec3 v;
      doc[i] >> v;
      std::cout << v.x << "\n";
      std::cout << v.y << "\n";
      std::cout << v.z << "\n";
   }

   return 0;
}

我认为,如果我类似地修改代码,Vec3 的内容会被计算出来,但事实并非如此。我究竟做错了什么?

4

1 回答 1

0

您的 YAML 文档是一系列“怪物”,而不是“向量”。要获得“位置”属性,您需要:

doc[i]["position"] >> v;

此外,您的 YAML 存在缩进错误(顶级序列未排列)。我假设它在您的文件中是正确的;在这里复制时要小心。

于 2011-02-25T20:45:41.720 回答